php名称空间和自动加载
|
我已经阅读了一些有关php 5.3+中的名称空间和自动加载的文章,但是仍然没有成功创建一个可以工作的:x也许你们中的一些人对我的代码出了什么问题有想法?
以前谢谢你。
Autoloader.php类
<?php
namespace my;
class AutoLoader {
private $aExt;
private $sPath;
protected static $instance;
public static function getInstance() {
if(!self::$instance instanceof self ) {
self::$instance = new self();
}
return self::$instance;
}
function __construct($sPath = __DIR__, $exts = \'php\') {
// define path and extensions to include
$this->setPath($sPath);
$this->setExtensions($exts);
}
public function getPath() {
return $this->sPath;
}
public function setPath($path){
$this->sPath = $path;
}
public function removePath() {
unset ($this->sPath);
}
public function addExtension($ext) {
// prepends period to extension if none found
$this->aExt[$ext] = (substr($ext, 0, 1) !== \'.\') ? \'.\'.$ext : $ext;
}
public function removeExtension($ext) {
unset ($this->aExt[$ext]);
}
public function getExtensions() {
return $this->aExt;
}
public function setExtensions($extensions) {
// convert
if (is_string($extensions)) {
$extensions = array($extensions);
}
// add
foreach($extensions as $ext) {
$this->addExtension($ext);
}
}
public function register() {
set_include_path($this->sPath);
// comma-delimited list of valid source-file extensions
spl_autoload_extensions(implode(\',\',$this->aExt));
// default behavior without callback
spl_autoload_register(array($this, \'autoload\'));
}
public function autoload($sClassName) {
include_once($sClassName.\'.php\');
return;
}
}
$autoloader = new AutoLoader();
$autoloader->register();
?>
MyClass.php我正在尝试加载的类
<?php
namespace my\\tools;
class MyClass {
function __construct() {}
function __destruct() {}
function test() {
echo \'ok\';
}
}
?>
index.php调用者
<?php
include_once(\'../Libraries/php/my/AutoLoader.php\');
new my\\tools\\MyClass();
?>
最后是我磁盘上的类结构
Libraries
|_php
|_my
| |_Autoloader.php
|
|_MyClass.php
没有找到相关结果
已邀请:
3 个回复
桑娠贯涤
孝铜差
期望有效的回调。您给...一些东西^^但不是回调。回调是
有关更多信息和示例,请参见手册:spl_autoload_register()。
犯痪桂涛杭