如果命名能遵守统一的约定
php是使用require(require_once)和include(include_once)关键字加载类文件。但是在实际的开发工程中我们根基上不会去使用这些关键字去加载类。 因为这样做会使得代码的维护相当的困难。实际的开发中我们会在文件的开始位置用use关键字使用类,然后直接new这个类就可以了. 至于类是怎么加载的,一般都是框架或者composer去实现的。
<?php use Illuminate\Container\Container; $container = new Container(); 自动加载我们可以通过一段伪代码来模拟一下在类的实例化工程中类是如何事情的
function instance($class) { // 如果类已加载则返回其实例 if (class_exists($class, false)) { return new $class(); } // 检察 autoload 函数是否被用户界说 if (function_exists('__autoload')) { __autoload($class); // 最后一次加载类的机会 } // 再次查抄类是否存在 if (class_exists($class, false)) { return new $class(); } else { // 系统:我实在没辙了 throw new Exception('Class Not Found'); } }php在语言层面供给了**__autoload** 魔术要领给用户来实现本身的自动加载逻辑。当用户去new一个类的时候,如果该类没有被加载,php会在抛堕落误前挪用**__autoload要领去加载类。下面的例子中的__autoload**要领只是简单的输出要加载类的名称, 并没有去实际的加载对应的类, 所以会抛堕落误。
<?php use Illuminate\Container\Container; $container = new Container(); function __autoload($class) { /* 具体措置惩罚惩罚逻辑 */ echo $class;// 简单的输出要加载类的名称 } /** * 运行功效 Illuminate\Container\Container Fatal error: Uncaught Error: Class 'Illuminate\Container\Container' not found in D:\project\php\laravel_for_ci_cd\test\ClassLoader.php:5 Stack trace: #0 {main} thrown in D:\project\php\laravel_for_ci_cd\test\ClassLoader.php on line 5 */大白了 **__autoload** 函数的事情道理之后,我们来用它去实现一个最简单自动加载。我们会有index.php和Person.php两个文件在同一个目录下。
//index.php <?php function __autoload($class) { // 按照类名确定文件名 $file = './'.$class . '.php'; if (file_exists($file)) { include $file; // 引入PHP文件 } } new Person(); /*---------------------支解线-------------------------------------*/ //Person.php class Person { // 东西实例化时输出当前类名 function __construct() { echo '<h1>' . __CLASS__ . '</h1>'; } } /**运行功效 * 输出 <h1>Person</h1> */ 定名空间定名空间并不是什么新鲜的事务,很多语言都早就撑持了这个特性(只是叫法不不异),它主要解决的一个问题就是定名斗嘴! 就仿佛日常生活中很多人城市重名,我们必需要通过一些标识来区分他们的差别。好比说此刻我们要用php介绍一个叫张三的人 ,他在财务部门事情。我们可以这样描述。
namespace 财务部门; class 张三 { function __construct() { echo '财务部门的张三'; } }这就是张三的根基资料 , namespace是他的部门标识,class是他的名称. 这样大家就可以知道他是财务部门的张三而不是工程部门的张三。
非限命名称,限命名称和完全限命名称
1.非限命名称,或不包罗前缀的类名称,例如 $comment = new Comment(); 如果当前定名空间是Blog\Article,Comment将被解析为、\Blog\Article\Comment。如果使用Comment的代码不包罗在任何定名空间中的代码(全局空间中),则Comment会被解析为\Comment。
注意: 如果文件的开头有使用use关键字 use one\two\Comment; 则Comment会被解析为 **one\two\Comment**。
2.限命名称,或包罗前缀的名称,例如 $comment = new Article\Comment(); 如果当前的定名空间是Blog,则Comment会被解析为\Blog\Article\Comment。如果使用Comment的代码不包罗在任何定名空间中的代码(全局空间中),则Comment会被解析为\Article\Comment。
3.完全限命名称,或包罗了全局前缀操纵符的名称,例如 $comment = new \Article\Comment(); 在这种情况下,Comment总是被解析为\Article\Comment。
spl_autoload
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31515.html
- 上一篇: 同步:一定要等任务执行完了
- 下一篇:JSOI2018 绝地还击