Reputation: 3207
I have some classes each in a file with the same name as the class itself. I want to dynamically load the related file from a given name and return the class object, but I have only the file/class name stored in a variable. How's that possible?
public function loadClass($name) {
include dirname(__FILE__) . '/classes/' . $name . '.php';
return $name;
}
Upvotes: 0
Views: 330
Reputation: 5754
<?php
spl_autoload_register(function ($name) {
$path = __DIR__ . '/classes/' . $name . '.php';
if (is_file($path)) {
require $path;
}
});
__DIR__
is equivalent to dirname(__FILE__)
.Multiple functions are processed as Queue, not Stack.
<?php
spl_autoload_register(function ($name) {
$path = __DIR__ . '/classes1/' . $name . '.php';
if (is_file($path)) {
require $path;
}
});
spl_autoload_register(function ($name) {
$path = __DIR__ . '/classes2/' . $name . '.php';
if (is_file($path)) {
require $path;
}
});
$foo = new Foo('bar');
./classes1/Foo.php
exists...$path
will be ./classes1/Foo.php
in the first function.require $path
will be called../classes2/Foo.php
exists...$path
will be ./classes1/Foo.php
in the first function.require $path
will be skipped.$path
will be ./classes2/Foo.php
in the first function.require $path
will be called.Upvotes: 1
Reputation: 1356
You should do it like this:
//test.php
class test {
public function shout() {
echo "Hello world!";
}
}
//main file
function loadClass($name) {
include(dirname(__FILE__) . '/classes/' . $name . '.php');
return new $name();
}
$class = loadClass('test');
$class->shout(); //prints Hello World!
For static approach, do this:
//test.php
class test {
static function shout() {
echo "Hello world!";
}
}
//main file
function loadClass($name) {
include(dirname(__FILE__) . '/classes/' . $name . '.php');
$name;
}
$class = loadClass('test');
$class::shout(); //prints Hello World!
Upvotes: 1
Reputation: 520
You can instantiate a new instance of the class with the $name
variable:
public function loadClass($name)
{
include dirname(__FILE__) . '/classes/' . $name . '.php';
return new $name();
}
Upvotes: 1
Reputation: 22711
Try this, You can use Autoloading
function __autoload($name) {
include dirname(__FILE__) . '/classes/' . $name . '.php';
}
You can call you class as,
$obj = new MyClass1();
Upvotes: 1