簡體   English   中英

無法通過spl_autoload_register加載帶有命名空間的PHP類?

[英]PHP classes with a namespace cannot be loaded via spl_autoload_register?

在類中實現名稱空間時,我在使用spl_autoload_register加載類時spl_autoload_register問題。

下面的類autoloader ,但是在沒有使用命名空間的情況下加載任何類都沒有問題,

class autoloader
{
    /**
     * Set the property.
     */
    public $directory;
    public $recursive;

    /**
     * Receive the supplied data.
     * @string $directory
     * @array $recursive default: models
     */
    public function __construct($directory, $recursive = array('search' => 'models') ) 
    {
        # Store the data into the property.
        $this->directory = $directory;
        $this->recursive = $recursive;

        # When using spl_autoload_register() with class methods, it might seem that it can use only public methods, though it can use private/protected methods as well, if registered from inside the class:
        spl_autoload_register(array($this,'get_class'));

    }

    private function get_class($class_name)
    {
        # List all the class directories in the array.
        if ($this->recursive)
        {
            $array_directories =  self::get_recursive_directory($this->directory);
        }
        else
        {
            if (is_array($this->directory)) $array_directories =  $this->directory;
            else $array_directories =  array($this->directory);
        }

        # Set the class file name.
        $file_name = 'class_'.strtolower($class_name).'.php';

        # Loop the array.
        foreach($array_directories as $path_directory)
        {
            if(file_exists($path_directory.$file_name)) 
            {
                # There is no need to use include/require_once. Autoload is a fallback when the system can't find the class you are instantiating. 
                # If you've already included it once via an autoload then the system knows about it and won't run your autoload method again anyway. 
                # So, just use the regular include/require - they are faster.
                include $path_directory.$file_name;
            } 
        }

    }

    # However the memory consumption of this can be huge if you have a very large directory tree with only a few matches.
    # @source: http://stackoverflow.com/questions/9294543/search-and-list-specific-directories-only
    public function get_recursive_directory($directory)
    {
        # Create an object that allows us to iterate directories recursively.
        # Stolen from here: 
        # http://www.php.net/manual/en/class.recursivedirectoryiterator.php#102587
        $iterator = new RecursiveIteratorIterator
                    (
                        new RecursiveDirectoryIterator($directory),
                        RecursiveIteratorIterator::CHILD_FIRST
                    );

        # This will hold the result.
        $result = array();

        # Loop the directory contents.
        foreach ($iterator as $path) 
        {

            # If object is a directory and matches the search term ('models')...
            if ($path->isDir() && $path->getBasename() === $this->recursive['search']) 
            {

                # Add it to the result array.
                # Must replace the slash in the class - dunno why!
                $result[] = str_replace('\\', '/', $path).'/';
                //$result[] = (string) $path . '/';

            }

        }

        # Return the result in an array.
        return $result;
    }
}

例如, tag類,

namespace hello;

class tag extends \core
{
}

現在通過autoloaderautoloader類,

# Autoload the classes from the specific folder.
$autoloader = new autoloader("C:/wamp/www/website/local/applications/master/sides/models/", $recursive = false);

# Instantiate the tag.
$tag = new hello\tag($connection);

結果,

致命錯誤 :類'你好\\標簽'用C未找到:\\ WAMP \\ WWW \\網站\\本地\\應用程序\\主\\線路7 兩邊\\意見\\ tags.php

知道如何修復我的autoloader類,以便我可以加載類,無論是否有命名空間?

編輯:

我保留類和類命名的文件夾,

C:\wamp\www\website\local\applications\master\sides\models\

class_tag.php
class_something.php

您的錯誤在您的get_class()方法中。 $class_name包含帶有命名空間的完全限定類名。 在您的情況下,您必須從類名中刪除命名空間。

$file_name = 'class_'.strtolower(array_pop(explode('\\', $class_name))).'.php';

我強烈建議使用PSR-0標准進行自動加載。 如果你將使用任何庫,很可能他們使用相同的標准,你只有一個自動加載器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM