[英]Cannot redeclare class: how to autoload a class if exists already in a folder?
如何檢查某個文件夾中是否已存在某個類,然后又不要從另一個文件夾再次加載該類?
例如,我有這種文件夾結構,
index.php
code/
local/
我在code/
和local/
有這兩個相同的類
來自本地/
class Article
{
public function getArticle()
{
echo 'class from local';
}
}
從核心
class Article
{
public function getArticle()
{
echo 'class from core';
}
}
因此,我需要一個腳本,該腳本可以檢測local/
的Article類- 如果該類已經存在於該文件夾中,則不再從core /文件夾中再次加載該類。 可能嗎?
這是index.php
用於加載類的自動加載功能,
define ('WEBSITE_DOCROOT', str_replace('\\', '/', dirname(__FILE__)).'/');
function autoloadMultipleDirectory($class_name)
{
// List all the class directories in the array.
$main_directories = array(
'core/',
'local/'
);
// Set other vars and arrays.
$sub_directories = array();
// When you use namespace in a class, you get something like this when you auto load that class \foo\tidy.
// So use explode to split the string and then get the last item in the exloded array.
$parts = explode('\\', $class_name);
// Set the class file name.
$file_name = end($parts).'.php';
// List any sub dirs in the main dirs above and store them in an array.
foreach($main_directories as $path_directory)
{
$iterator = new RecursiveIteratorIterator
(
new RecursiveDirectoryIterator(WEBSITE_DOCROOT.$path_directory), // Must use absolute path to get the files when ajax is used.
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $fileObject)
{
if ($fileObject->isDir())
{
// Replace any backslash to '/'.
$pathnameReplace = str_replace('\\', '/', $fileObject->getPathname());
//print_r($pathnameReplace);
// Explode the folder path.
$array = explode("/",$pathnameReplace);
// Get the actual folder.
$folder = end($array);
//print_r($folder);
// Stop proccessing if the folder is a dot or double dots.
if($folder === '.' || $folder === '..') {continue;}
//var_dump($fileObject->getPathname());
// Must trim off the WEBSITE_DOCROOT.
$sub_directories[] = preg_replace('~.*?(?=core|local)~i', '', str_replace('\\', '/', $fileObject->getPathname())) .'/';
}
}
}
// Mearge the main dirs with any sub dirs in them.
$merged_directories = array_merge($main_directories,$sub_directories);
// Loop the merge array and include the classes in them.
foreach($merged_directories as $path_directory)
{
if(file_exists(WEBSITE_DOCROOT.$path_directory.$file_name))
{
// There is no need to use include/require_once. Autoload is a fallback when the system can't find the class you are instantiating.
// If you've already included it once via an autoload then the system knows about it and won't run your autoload method again anyway.
// So, just use the regular include/require - they are faster.
include WEBSITE_DOCROOT.$path_directory.$file_name;
}
}
}
// Register all the classes.
spl_autoload_register('autoloadMultipleDirectory');
$article = new Article();
echo $article->getArticle();
我當然會收到這個錯誤,
Fatal error: Cannot redeclare class Article in C:\wamp\...\local\Article.php on line 3
我應該研究class_exists的答案,但是如何與上面的函數一起使用它, 尤其是 spl_autoload_register
。 或者,如果您有更好的主意?
好吧,我誤會了你的問題。 這應該可以解決問題。
<?php
function __autoload($class_name) {
static $core = WEBSITE_DOCROOT . DIRECTORY_SEPARATOR . "core";
static $local = WEBSITE_DOCROOT . DIRECTORY_SEPARATOR . "local";
$file_name = strtr($class_name, "\\", DIRECTORY_SEPARATOR):
$file_local = "{$local}{$file_name}.php";
require is_file($file_local) ? $file_local : "{$core}{$file_name}.php";
}
通過使用名稱空間可以輕松解決此問題。
您的核心文件進入/Core/Article.php
:
namespace Core;
class Article {}
您的本地文件轉到/Local/Article.php
:
namespace Local;
class Article {}
然后使用一個非常簡單的自動加載器,例如:
function __autoload($class_name) {
$file_name = strtr($class_name, "\\", DIRECTORY_SEPARATOR);
require "/var/www{$file_name}.php";
}
PHP按需加載類,無需預先加載文件!
如果您只想使用文章,請執行以下操作:
<?php
$coreArticle = new \Core\Article();
$localArticle = new \Local\Article();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.