开发者

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 execu开发者_如何学运维te.

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


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


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?


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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜