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!
I'd like to be able to include a lot of arrays into a class I have put together. I use the arrays elsewhere on the site but the class also needs to use them.
Originally I had the arrays in 2 places (in the class and duplicated in another file for the rest of the site to use) but I would like to just have it all in one place but I can't seem to include() in a class.
include("pathToMy/include_file.php");
class myClass{
//the rest of my class code goes in here
}
That way all variables in file "include_file.php" will have global scope within the class, if that is what you intend. For more info reg. scope see http://www.php.net/variables.scope
The reason your example produced an error was because you included it in the wrong place. You can't include between class definition, methods and/or constructor. You can declare class properties there, but that's it.
patrikG wrote:
The reason your example produced an error was because you included it in the wrong place. You can't include between class definition, methods and/or constructor. You can declare class properties there, but that's it.
patrikG wrote:
The reason your example produced an error was because you included it in the wrong place. You can't include between class definition, methods and/or constructor. You can declare class properties there, but that's it.
class myClass
{
function myClass ()
{
include("pathToMy/inlude_file.php");
}
//the rest of my class code goes in here
}
Sorry to be nitpicking (don't ask me, it's apparently one of those days), the class-method you've defined there is called the constructor as it gets executed every time you instantiate the class. A method only gets executed when explicitely called.
class myClass
{
function myClass ()
// the constructor of the class
{
include("pathToMy/inlude_file.php");
}
function IAmAMethod($some_arguments){
...
}
} //the rest of my class code goes in here
}