Reputation: 40633
There are a list of PHP files in the same directory of my script. They all follow a naming convention (e.g. class.foo.php). When my script runs, I want it to include those files. It's simple enough to do a scandir
of the files, do a test in each item in the resulting array, and include
the file.
The problem is how do I create an instance of those classes in my script (which is a class, also)? The file class.foo.php
will have class Foo
in it. I need to create an instance of Foo
(and sometimes just access a static method). I can't do this in the running script because it is not aware of the auto-included classes.
get_included_files
is useless because because it returns all the included files in the chain of classes (and I'm only interested in the classes included in the running script).
Perhaps I'm going about this the wrong way. What's a way for me to "auto include" class files and use them in the running script?
Upvotes: 2
Views: 3191
Reputation: 7791
You can use __autoload()
magic method. See this example:
./myClass.php
<?php
class myClass {
public function __construct() {
echo "myClass init'ed successfuly!!!";
}
}
?>
./index.php
<?php
// we've writen this code where we need
function __autoload($classname) {
$filename = "./". $classname .".php";
include_once($filename);
}
// we've called a class ***
$obj = new myClass();
?>
Output:
myClass init'ed successfuly!!!
Read more at:
Upvotes: 2
Reputation: 35337
Create an autoload function and register it: spl_autoload_register
A proper autoload function will load the corresponding file when a class is instantiated.
Example from php.net:
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
Upvotes: 5