调用类常量时,PHP Autoloader会加载吗?
作者:互联网
我有一个定义一些类常量的类.为简单起见,它看起来像这个假的类.
class MyThing {
const BORIS = 'Yeltsin';
}
我正在注册该类所在的目录.
AutoLoader::registerDirectory('lib');
我正在使用PHP的自动加载器,它按预期工作,除非我试图调用此类const.
如果我这样做
MyThing::BORIS
我明白了
Undefined class constant 'BORIS'
我认为这就是自动加载器应该如何工作,但我想知道我是否正确.
我正在使用这个AutoLoader类,这是在我开始在这家公司工作之前选择的,但它似乎有效.
<?php
/**
* Autoloading class.
* From http://jes.st/2011/phpunit-bootstrap-and-autoloading-classes/
* as per the author comment:
* Jess Telford says:
* December 21, 2013 at 4:01 am
* Public Domain – do with it whatever you want :)
*
* This class will compare classnames to the filename without extensions (.class.php or .php) registered
*
* This means that only a class per file can be loaded and only if the class name is identical (case sensitive) to the file name
*
*/
class AutoLoader {
static private $classNames = array();
/**
* Recursively store all .class.php and .php files found under $dirName in the autoloader
*
* @param String $dirName has to be a valid path
*/
public static function registerDirectory($dirName) {
$di = new DirectoryIterator($dirName);
foreach ($di as $file) {
if ($file->isDir() && !$file->isLink() && !$file->isDot()) {
self::registerDirectory($file->getPathname());
} elseif (substr(strtolower ($file->getFilename()), -10) === '.class.php') {
$className = substr($file->getFilename(), 0, -10);
AutoLoader::registerClass($className, $file->getPathname());
}elseif (substr(strtolower ($file->getFilename()), -4) === '.php') {
$className = substr($file->getFilename(), 0, -4);
AutoLoader::registerClass($className, $file->getPathname());
}
}
}
public static function registerClass($className, $fileName) {
AutoLoader::$classNames[$className] = $fileName;
}
public static function loadClass($className) {
if (isset(AutoLoader::$classNames[$className])) {
require_once(AutoLoader::$classNames[$className]);
}
}
}
spl_autoload_register(array('AutoLoader', 'loadClass'));
?>
更新:我原来的问题说调用spl_autoload(‘MyThing’)解决了我的问题,但事实并非如此.
解决方法:
简而言之,是的,autoloader被称为静态.
你可以自己测试一下:
的index.php
<?php
class Init {
function __construct() {
spl_autoload_register(array($this, 'loadClass'));
echo MyThing::BORIS;
}
function loadClass($className) {
$possible_file = 'classes/' . strtolower($className) . '.php';
echo 'Autoloader called for ' . $className . '<br />';
if(file_exists($possible_file)) {
require_once($possible_file);
return true;
}
return false;
}
}
new Init();
/classes/mything.php
<?php
class MyThing {
const BORIS = 'Yeltsin';
}
产量
Autoloader called for MyThing
Yeltsin
标签:php,autoloader 来源: https://codeday.me/bug/20190623/1275546.html