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条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了