I want to return an error message when two classes provided by the user/ developer don't exist.
core/model/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';
}
}
local/model/Conan.php,
namespace local\model;
class Conan
{
var $bodyBuild = 'very skinny';
var $birthDate = '1963';
var $skill = 'comedy';
public function methodConan()
{
return 'The methodConan from namespace local\model';
}
}
index.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';
}
}
I suppose to get 'both don\'t exist'
as the result, I get this error instead,
Fatal error: Cannot redeclare class local\model\Conan in C:\wamp\www...\local\model\Conan.php on line 8
It doesn't really make sense!
Is it something wrong with my autoload below??
autoload class,
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;
}
}
}
}
try using require_once
instead of include