错误:无缘无故地调用类

时间:2016-04-12 01:10:13

标签: php

错误是:

  

未找到“控制器\索引”类

但是在我的所有代码中我都会打电话给这个班级:

Test.php <<脚本执行者

include_once("index.engine.php");
Index::importController();
use Controller\User;
echo User::getWorld(); // The error happens here.

Index.engine.php <<索引器包括

if (!defined('HOME')) define("HOME", __DIR__."/");

class Index{

    public static function importModel(){           
        spl_autoload_register(function ($class) {
            $nome = str_replace("\\", "/" , $class . '.model.php');
            if( file_exists( HOME . $nome ) ){
                include_once( HOME . $nome );
            }
        });
    }

    public static function importController(){
        spl_autoload_register(function ($class) {
            $nome = str_replace("\\", "/" , $class . '.controller.php');
            if( file_exists( HOME . $nome ) ){
                include_once( HOME . $nome );
            }
        });
    }

    public static function importPersistent(){
        spl_autoload_register(function ($class) {
            $nome = str_replace("\\", "/" , $class . '.persistent.php');
            if( file_exists( HOME . $nome ) ){
                include_once( HOME . $nome );
            }
        });
    }

}

user.controller.php <<只有中介

        namespace Controller{
    include_once (__DIR__ ."/../index.engine.php");
    Index::importPersistent();
    use Persistent\Test;
        class User{ 
            public static function getWorld(){
                $result = Test::getEngine(); 
                return $result;
            }
        }
    }

user.persistent.php <<需要的功能

namespace Persistent{
    class Test{
        public static function getEngine(){
            $engine = "Engine is on! \o/";
            return $engine;
        }
    }
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

use Controller\User; # this is used to call a namespace, in your code there is no declaration of the namespace
echo User::getWorld(); // 

为此,我们应该有一个这种形式的文件

sample.php

namespace Controller;

class User {
   public static function getWorld() {
     ...
   }
}

答案 1 :(得分:0)

<强> user.controller.php

namespace Controller{
include_once (__DIR__ ."/../index.engine.php");
Index::importPersistent();
use Persistent\Test;
    class User{ 
        public static function getWorld(){
            $result = Test::getEngine(); 
            return $result;
        }
    }
}

我改为:

namespace Controller{
use Index;
use Persistent\Test;
Index::importPersistent();
    class User{ 
        public static function getWorld(){
            $result = Test::getEngine(); 
            return $result;
        }
    }
}

错误发生在被多次调用的include中,然后被更改为在视图中只调用一次。