dave
dave

Reputation: 7857

Having trouble dynamically loading a class in PHP

Here's what the class loader looks like:

loader.php

class Load
{
    public static function init($class)
    {
        require_once 'classes/' . $class . '.php';
        return new $class();
    }
}

$class = Load::init('MyClass');

The error being returned is:

Fatal error:  Class 'MyClass' not found in /www/website/application/models/Database/loader.php on line 5

If I put an echo 'WORKS'; into MyClass.php, I can see that it isn't being included. That echo doesn't execute.

UPDATE: It seems I've been editing a cached version of my code and not the actual file... The code works :}

Upvotes: 0

Views: 536

Answers (4)

takeshin
takeshin

Reputation: 50638

Three tips:

  1. You should use Zend_Autoloader or subclass one of the Zend's autoloaders if you are using Zend Framework. To use Zend Autoloader you need to configure autoloader namespace, e.g. in application.ini and name/place your files according to PEAR (Zend) naming convention.
  2. You should use absolute path, because relative paths may vary and point to other resources, e.g. APPLICATION_PATH . '/../your/path'
  3. Check the file permissions/ownership

Upvotes: 0

prodigitalson
prodigitalson

Reputation: 60413

Could be a couple things...

  • What is the filesystem path to classes/? Is it on your include path? If not, you need to use the absolute path.

  • If youre on *nix, most of them use a case sensitive filesystem - is you file named MyClass.php or myclass.php?

Upvotes: 0

Phil
Phil

Reputation: 164730

Does classes/MyClass.php contain a class definition for MyClass?

I'm assuming the require was able to find classes/MyClass.php on the include path, but is it loading the correct file?

Upvotes: 0

castis
castis

Reputation: 8223

Try this.

function __autoload($class_name) {
    include $class_name . '.php';
}

Put that anywhere publically accessable to the rest of your code. At that point, when you do something like this.

$class = new Foobar();

If the class is not already included, php will run that __autoload function and include the file for you. Make sure you point that include statement to wherever your classes are stored.

For more information on that, check out the php doc here.

http://php.net/manual/en/language.oop5.autoload.php

Upvotes: 2

Related Questions