include vs require
被包含文件查找顺序:给出的路径-include path-调用脚本文件的目录和当前工作目录;
include:未找到发出警告,会继续执行,文件执行每次都进行读取和评估;
require:未找到发出致命错误,不会继续执行,文件只处理一次(实际上,文件内容替换require语句),效率较高;
include_once:如果已包含文件,不会再次包含;
require_once同理。
命名空间
声明:脚本第一条可执行语句!!除了declare可以在namespace前,其余任何代码都不可以!
//newfile.php
<?php
namespace newfile;
class newfile{
function __construct(){
echo "This is construct.";
}
}
//main.php
<?php
use newfile\newfile;
$file = new newfile();
这样我们执行以下main。出现了Uncaught Error错误。。
请注意,使用命名空间只是让类名有了前缀,不容易发生冲突,系统仍然不会进行自动导入。
spl_autoload_register实现自动加载
事实上,实例化的过程中,系统首先在当前目录中找寻class,如果不存在,查看是否自定义__autoload函数,最后再次判断类是否存在。如果自定义了spl_autoload_register()函数,zf引擎会将__autoload函数取代为spl_autoload();
由于spl_autoload_register更加灵活,推荐使用,__autoload可能会被之后的php版本舍弃。
spl_autoload_register() 函数功能把传入的函数注册到spl_autoload函数队列中,而不执行默认的autoload函数。
<?php
//main.php
use newfile\newfile;
spl_autoload_register(function ($class){
$classmap = array(
// 限定类名 => 文件
'newfile\newfile'=>'./newfile.php',
);
if (!file_exists($class)) {
include $classmap[$class];
}
});
new newfile();
PSR0 以及 PSR4
psr0与psr4是两种通用自动加载器的规范;psr4是对psr0的补充。
每个命名空间(namespace)都必须有一个顶级的空间名(namespace)(“组织名(Vendor Name)”)。解析\app\newfile,如果Project 对应的是 ./app,那么文件绝对路径应该是 ./app/newfile.php。
<?php
use app\newfile\newfile;
function autoload($className)
{
$classMap=array(
'app' =>'./app'
);
$vendor = substr($className, 0,strpos($className, '\\')); //app
$vendorDir = $classMap[$vendor]; //./app
$fileName =basename($className).'.php'; //newfile.php
$fileName = $vendorDir.DIRECTORY_SEPARATOR.$fileName;
if (is_file($fileName)) {
require_once $fileName;
}
}
spl_autoload_register('autoload');
$file = new newfile();
//输出 This is construct.
Composer对PSR4的处理
自动生成的PSR4配置文件名称为autoload_psr4.php
psr0为autoload_namespace.php
配置文件返回一个关联数组,键是名称空间的前缀,值是名称空间前缀对应的路径
'PhpParser\\' => array($vendorDir . '/nikic/php-parser/lib/PhpParser')