PHP: Autoloading PEAR namespaced classes within PSR-0 namespaced classes conflict

谁说胖子不能爱 提交于 2019-12-11 13:52:53

问题


For my application I am using PSR-0 namespaces. Everything works beautiful!

Until I wanted to use Twig as template parser, Twig uses PEAR pseudo namespaces. Like Twig_Loader_Filesystem.

The problem is that when I want to use Twig inside my name-spaced application like this:

<?php
namespace Tact\ViewManager;

class ViewManager {

    public function init()
    {
        $loader = new Twig_Loader_Filesystem($this->templatepath);
        $this->twig = new Twig_Environment($loader);
    }  
}
?>

PHP will tell my autoloader to look for an class named Tact\ViewManager\Twig_Loader_Filesystem

How can I manage to autoload PEAR name-spaced style classes without the PSR-0 namespace of the invoking class?

My autoloader is able to load both PEAR and PSR-0..

Thanks in advance!


回答1:


This is because you are in the Tact\ViewManager namespace. The pseudo-namespaced classes are in fact in the global namespace, so you should prefix them with \ to call them:

$loader = new \Twig_Loader_Filesystem($this->templatepath);

If the \ prefix bugs you, you could do this:

namespace Tact\ViewManager;

use Twig_Loader_Filesystem;
use Twig_Environment;

class ViewManager {
    public function init()
    {
        $loader = new Twig_Loader_Filesystem($this->templatepath);
        $this->twig = new Twig_Environment($loader);
    }  
}



回答2:


Try this:

    $loader = new \Twig_Loader_Filesystem($this->templatepath);
    $this->twig = new \Twig_Environment($loader);

This will tell PHP to force namespace\class lookup at "root" level, and if your autoloader is setup to load both namespaces and regular PEAR convention classnames it will work.



来源:https://stackoverflow.com/questions/12386594/php-autoloading-pear-namespaced-classes-within-psr-0-namespaced-classes-conflic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!