functions within classes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SBro
Forum Commoner
Posts: 98
Joined: Tue Sep 30, 2003 10:06 pm

functions within classes

Post by SBro »

I have two files one with miscellanous functions (call this x.php) in it and the other with a class (with associated functions, call this y.php).

Now in y.php I use a function that is contained in x.php. When I wrote the code I initially thought that I would have to include x.php in y.php if I wanted to use a function from it. However when it came time to run the code I got the error:

Fatal error: Cannot redeclare connectdb() (previously delcared....)

So I took the include part out of my code and now it works fine. So my question is: how come this works? how does php know where to pick this function from? thankyou.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it sounds like your running script looks like this:

Code: Select all

<?php

include('x.php');
include('y.php');

?>
in which case, all the functions and things that were created in x.php are completely available for y.php.. you can still include x.php in y.php, but instead of using "include" use "include_once". It can be suggested to nearly always use "include_once" and it's sibling, "require_once" .. there are cases where "include" and "require" are useful..

me being lazy in making sure I only include files once, I just include_once all the files each script needs.. Just in case someone else decides to include that one file if I ever leave that project 8O :D
SBro
Forum Commoner
Posts: 98
Joined: Tue Sep 30, 2003 10:06 pm

Post by SBro »

Ahh, silly me, of course, heh, thanks for that Feyd. So is this the "proper" way of doing things? ie. just including the file in the running script? (have used include_once as suggested).
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

If y.php needs functions from x.php then i'd include_once x.php from the top of y.php, this frees you from having to remember that y.php also requires x.php (i.e y.php takes care of itself).
If you just need functions from x.php in a script then you can just require x.php in the script.
Post Reply