duanquan1876 2013-05-27 19:34
浏览 125
已采纳

找不到命名空间问题类

In my root folder I have a file folder that has my common files I use between different projects. /files I have a file redis.php that has Redis class that I want to use in one of my project in /var/www/html/project/example.php The Class Redis is in /file/library/storage/redis/redis.php

my redis.php has

<?php

    namespace file\library\storageedis;

    class Redis{

        public function init(){
            $redis = new Redis();
            $redis->connect('127.0.0.1', 6379);
        }


    }



?>

and in my example.php I call that namespace like

$redis = new \file\library\storageedis\Redis();
$redis->init();

but it gives me an error

[Mon May 27 12:25:48 2013] [error] [client 127.0.0.1] PHP Fatal error:  Class 'file\\library\\storage\edis\\Redis' not found

Any help will be appreciated

  • 写回答

2条回答 默认 最新

  • doufeixuan8882 2013-05-27 19:57
    关注

    What you are looking for is an autoloader that can map your namespaces to actual paths and include the class files before you're creating an instance of them. Take a look at the commonly used PSR-0 autoloader.

    <?php
    
    function autoload($className)
    {
        $className = ltrim($className, '\\');
        $fileName  = '';
        $namespace = '';
        if ($lastNsPos = strrpos($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;
    }
    spl_autoload_register('autoload');
    

    If you include this code in /var/www/html/project/example.php, what happens then when you try to make an instance

    $redis = new \file\library\storageedis\Redis(); 
    

    Is that it will try to include this file first

    /var/www/html/project/file/library/storage/redis/Redis.php
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作