gpt4 book ai didi

PHP class_exists - 出现 fatal error : Cannot redeclare clas instead?

转载 作者:行者123 更新时间:2023-12-04 16:52:14 26 4
gpt4 key购买 nike

我要退货错误 消息时 两个用户/开发人员提供的类不存在。

核心/模型/Conan.php,

namespace core\model;

class Conan
{
var $bodyBuild = 'extremely muscular';
var $birthDate = 'before history';
var $skill = 'fighting';

public function methodConan()
{
return 'The methodConan from namespace core\model';
}
}

本地/模型/Conan.php,

命名空间本地\模型;
class Conan 
{
var $bodyBuild = 'very skinny';
var $birthDate = '1963';
var $skill = 'comedy';

public function methodConan()
{
return 'The methodConan from namespace local\model';
}
}

索引.php,
define ('WEBSITE_DOCROOT', str_replace('\\', '/', dirname(__FILE__)).'/');

include 'core/helper/BaseClassAutoloader.php';

// Autoload the core & local classes.
$autoloader = new BaseClassAutoloader([
'local/model/',
'core/model/'
]);

if (class_exists('\foo\model\Conan'))
{
echo 'from local';
}
else
{
if(class_exists('\boo\model\Conan'))
{
echo 'from core';
}
else
{
echo 'both don\'t exist';
}

}

我想得到 'both don\'t exist'结果,我得到了这个错误,

Fatal error: Cannot redeclare class local\model\Conan in C:\wamp\www...\local\model\Conan.php on line 8



这真的没有意义!

我下面的自动加载有问题吗??

自动加载类,
class BaseClassAutoloader
{
public function __construct($directory)
{
$this->directory = $directory;

spl_autoload_register(array($this,'getClass'));
}

private function getClass($class_name)
{
if(is_array($this->directory)): $mainDirectories = $this->directory;
else: $mainDirectories = array($this->directory); endif;

$subDirectories = [];

$namespace = "\\";
$isNamespace = false;

$parts = explode($namespace, $class_name);

if(strpos($class_name, $namespace) !== false)
{
$isNamespace = true;
}

$fileNameName = end($parts).'.php';

foreach($mainDirectories as $pathDirectory)
{
$iterator = new RecursiveIteratorIterator
(
new RecursiveDirectoryIterator(WEBSITE_DOCROOT.$pathDirectory), // Must use absolute path to get the files when ajax is used.
RecursiveIteratorIterator::SELF_FIRST
);

foreach ($iterator as $fileObject)
{
if ($fileObject->isDir())
{
$pathnameReplace = str_replace('\\', '/', $fileObject->getPathname());

$array = explode("/",$pathnameReplace);

$folder = end($array);

if($folder === '.' || $folder === '..') {continue;}

$subDirectories[] = preg_replace('~.*?(?=core|local)~i', '', str_replace('\\', '/', $fileObject->getPathname())) .'/';
}
}
}


$merged_directories = array_merge($mainDirectories,$subDirectories);

foreach($merged_directories as $pathDirectory)
{
if(file_exists(WEBSITE_DOCROOT.$pathDirectory.$fileNameName))
{
include WEBSITE_DOCROOT.$pathDirectory.$fileNameName;

if($isNamespace === false) if (class_exists($class_name)) break;
}
}
}

}

最佳答案

尝试使用 require_once而不是包含

关于PHP class_exists - 出现 fatal error : Cannot redeclare clas instead?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26844841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com