Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class not found - using "use"

Tags:

php

After 4 years of absence in PHP programming I'm trying to make some new project in it.

I'm collecting some useful libraries. And I have problem with "use" keyword. Here is my part of code where error is thrown.

<?PHP

    use Assetic\Asset\AssetCollection;
    use Assetic\Asset\FileAsset;
    use Assetic\Asset\GlobAsset;

    $js = new AssetCollection(array(
    ...
?>

And I'm getting error:

Fatal error: Class 'Assetic\Asset\AssetCollection' not found in /home/php/index.php on line 7

I thought that is maybe something wrong with include_path in php.ini, but it looks like that:

include_path = ".:/usr/share/php5:/usr/share/php"

Did I miss something?

BTW. I'm using nginx + php-fpm.

like image 945
ThomK Avatar asked Aug 05 '11 19:08

ThomK


1 Answers

The use keyword does not actually include any files. I'm afraid you either have to register an autoload function with the spl_register_autoload() call, or manually include the files.

http://www.php.net/manual/en/function.spl-autoload-register.php

Usually a good default autoloader will look for files following the same path as the namespaces, like this:

spl_autoload_register(
    function($className)
    {
        $className = str_replace("_", "\\", $className);
        $className = ltrim($className, '\\');
        $fileName = '';
        $namespace = '';
        if ($lastNsPos = strripos($className, '\\'))
        {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }
        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

        require $fileName;
    }
);

More on autloading in PHP, a structure that many (newer) projects are following: http://groups.google.com/group/php-standards/web/psr-0-final-proposal

like image 64
Pelshoff Avatar answered Nov 02 '22 22:11

Pelshoff