Modern PHP(二)标准
psr1-4 规范
psr-1
php标签: <?php
编码:utf8
自动加载:命名空间和类需满足psr4的规范
类的名称:驼峰式 CameCase
常量:全部大写,下划线分开 GREAT_SCORE
方法名:首字母小写驼峰,cameCase
psr-2
缩进:四个空格 代替 tab
关键字:统一使用小写,false true null
命名空间:命名空间后需空一行,use后面也空一行
方法和类括弧:统一单独一行
psr-3
日志记录接口
日志类需实现 Psr\Log\LoggerInterface接口
日志可使用成熟第三方拓展 monolog/monolog,而不必重复写
psr-4 自动加载器
composer会生成自动加载器,而不需要手动编写
手写自定义加载器
spl_autoload_register(function($class){
//项目命名空间前缀
$prefix = 'Foo\\Bar\\';
//命名空间前缀对应的基目录
$base_dir = __DIR__.'/src/';
$len = strlen($prefix);
//实例化的类的命名空间,是否和项目命名空间一致(不一致则让其他加载器加载)
if(strncmp($prefix, $class, $len) !== 0){
return;
}
$relative_class = substr($class, $len);
$file = $base_dir.str_replace('\\', '/', $relative_class).'.php';
if(file_exists($file)){
require $file;
}
});
$class = new \Foo\Bar\Student();
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: