Farid Rn
Farid Rn

Reputation: 3207

How to load a class by it's name stored in a variable

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

Answers (4)

mpyw
mpyw

Reputation: 5754

Solution

<?php
spl_autoload_register(function ($name) {
    $path = __DIR__ . '/classes/' . $name . '.php';
    if (is_file($path)) {
        require $path;
    }
});
  • __DIR__ is equivalent to dirname(__FILE__).
  • You can define multiple autoload functions with spl_autoload_register.
  • You should check file existence.

Multiple Auto-Loading Example

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');

if ./classes1/Foo.php exists...

  1. $path will be ./classes1/Foo.php in the first function.
  2. require $path will be called.

if ./classes2/Foo.php exists...

  1. $path will be ./classes1/Foo.php in the first function.
  2. require $path will be skipped.
  3. $path will be ./classes2/Foo.php in the first function.
  4. require $path will be called.

Upvotes: 1

makallio85
makallio85

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

Morten Bjerg Gregersen
Morten Bjerg Gregersen

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

Krish R
Krish R

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

Related Questions