所以我之前已经在这里问过这个问题,但是提供的解决方案对我不起作用。 这是我的设置:
/mylib
/Vendor/Module/MyClass.php
/document_root
index.php
这是我的 index.php
<?php
define('CLASSDIR', 'mylib');
define('BASEPATH', @realpath( dirname (__FILE__).'/../').'/'.CLASSDIR);
spl_autoload_register(null, false);
spl_autoload_extensions('.php');
function autoLoader($className){
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
echo 'does it come here? nope.';
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= BASEPATH.'/'.str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
}
spl_autoload_register('autoLoader');
//$obj = new MyClass();
$obj = new \Vendor\Module\MyClass();
$obj::test();
?>
这是我的 MyClass.php
<?php
namespace Vendor\Module;
class MyClass{
public function __construct(){
echo 'weird';
}
public function test(){
echo 'strange';
}
}
?>
我的 echo 没有显示任何东西。显然我的课也没有加载。相反,我得到了这个错误。
Fatal error: Call to undefined method MyClass::test() in /<documentroot>/index.php on line 29
请帮忙。我已经坚持了很长一段时间,而我的其余发展都在受苦。我尝试移动到 spl_autoload_register()
只是因为这是推荐的方式。现在失去的时间让我后悔。
最佳答案
您错误地调用了 test()
函数(使用静态方式?)。
调用函数:
$obj = new MyClass();
$obj->test();
如果您打算使用像 MyClass::test()
这样的静态方法,请在您的类中将您的函数声明为:
public static function test() {
}
此外,您的自动加载器过于复杂。可以简化为:
$class_dir = array(
'/mylib/Vendor/Module/',
// Add more paths here ( or you can build your own $class_dir )
);
function class_loader($class_name) {
global $class_dir;
foreach ($class_dir as $directory) {
if (file_exists($directory . $class_name . '.php')) {
require_once($directory . $class_name . '.php');
return;
}
}
}
spl_autoload_register('class_loader');
第三次编辑:
我注意到你设置的路径不正确。
$fileName .= BASEPATH.'/'.str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
应该是:
$filename = BASEPATH .'/' . $filename . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
如前所述,可以通过回显$filename
的值轻松调试它。
关于php - 加载类时 spl_autoload_register 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19556728/