Page 1 of 1

functions within classes

Posted: Thu Aug 26, 2004 9:50 pm
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.

Posted: Thu Aug 26, 2004 10:41 pm
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

Posted: Thu Aug 26, 2004 10:53 pm
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).

Posted: Thu Aug 26, 2004 10:56 pm
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.