我发现了几个与我类似的 SO 问题,但我正在努力寻找对我有帮助的答案,而且我真的很想知道自动加载命名空间中存在的类的最佳实践。
我的文件夹结构:
root
-- classes
--- Users
---- Users.class.php
和users.php;
<?php
namespace CompanyName\ProjectName\Users;
class UserMapper
{
// class code here
}
还有我的自动加载功能,它位于根文件夹中;
/* autoload classes on instatiation */
spl_autoload_register(function($class)
{
include $_SERVER['DOCUMENT_ROOT'] . '/classes/' . $class . '.class.php';
});
而且,假设我像这样调用用户类;
<?php
new \CompanyName\ProjectName\User();
警告:包括(/Applications/XAMPP/xamppfiles/htdocs/test_tool/classes/CompanyName\ProjectName\User.class.php):无法打开流:没有这样的文件或目录...等
要使用 spl_autoload_register,是否需要将文件夹结构映射到命名空间结构?我不想这样做,因为我喜欢将我的类(class)放在同一个文件夹中,并在其中包含子文件夹。
或者我是否向我的自动加载功能添加了额外的代码?
我也搜索了php手册,没有工作命名空间示例,我觉得很奇怪。
任何帮助将非常感激。
提前致谢。
最佳答案
Disclaimer: I am a beginer at php, my answer may not be correct but i'm confident examining and testing the example bellow will help clarify the use of Namespaces with spl_autoload_register for any beginner like me.
考虑这个文件夹结构:
- root/ contains index.php.
- root/model/ contains A.php & AA.php
一个.php :
?php
namespace company\model;
use \company\model\A;
class A
{
public function speak()
{
echo 'hello world! ';
}
}
AA.php :
?php
namespace company\model;
use \company\model\A;
require_once 'A.php';
class AA extends A
{
public function shout()
{
echo 'HELLO WOORLD!!!';
}
}
索引.php :
<?php
namespace company;
use \company\model\A;
function classLoader ($className)
{
if (file_exists($className.'.php'))
{
require_once $className.'.php';
} else {
$className = str_replace('\\', '/', $className);
$className = str_replace('company/', '', $className);
if (file_exists($className.'.php'))
require_once $className.'.php';
else
throw new EXCEPTION('classLoader could not find '.$className.'.php .');
}
}
spl_autoload_register(classLoader);
$obj = new A;
//we dont need to write ($obj = new \company\model\A;)
//because of statement at line 4
$obj->speak();
echo '<br/>';
$objA = new \company\model\AA;
$objA->shout();
echo '<br/>';
class AB extends \company\model\AA
{
public function doBoth()
{
$this->speak();
$this->shout();
}
}
$objB = new AB;
$objB->doBoth();
关于php - 命名空间和 spl_autoload_register,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34092806/