一:分级的命名空间自动加载类
代码图:
部分代码:
实例
<?php
namespace _1010;
use _1010\t2\test2;//
use _1010\t3\test3;
spl_autoload_register(function ($className){
$path = str_replace('_1010'.'\\',DIRECTORY_SEPARATOR,$className);
$path = str_replace('\t2'.'',DIRECTORY_SEPARATOR,$path);
$path = str_replace('\t3'.'',DIRECTORY_SEPARATOR,$path);
$path = __DIR__.'/'.$path.'.php';
//die($path);
include $path;
});
echo test1::get();
echo '<br>';
echo test2::get();
echo '<br>';
echo test3::get();
运行实例 »点击 "运行实例" 按钮查看在线实例
二:trait类的理解
实例
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019\10\15 0015
* Time: 10:42
*/
class fu
{
public function a()
{
echo '我是父类的a'.'<br>';
}
public function b()
{
echo '我是父类的b'.'<br>';
}
public function c()
{
echo '我是父类的c'.'<br>';
}
}
// 不直接变动父类, 通过 traits 增加新的方法集, 或修改父类方法
trait traits
{
public function a()
{
echo '我是trait的a'.'<br>';
}
public function b()
{
echo '我是trait的b'.'<br>';
}
}
//子类
class zi extends fu
{
// 引入trait类
use traits;
public function a()
{
echo '我是子类的a'.'<br>';
}
}
$boj = new zi();
//方法的优先级为 : 子类覆盖 --->trait类覆盖 ---> 父类
$boj->a();
$boj->b();
$boj->c();
运行实例 »点击 "运行实例" 按钮查看在线实例
总结:
空间自动加载类引入的时候,没有写别名,就使用类名调用
trait类方法的优先级为 : 子类覆盖 --->trait类覆盖 ---> 父类,子类中使用use关键字引入trait类 ,可以解决类单继承的问题
Correction status:qualified
Teacher's comments:不必这样:
$path = str_replace('_1010'.'\\',DIRECTORY_SEPARATOR,$className);
$path = str_replace('\t2'.'',DIRECTORY_SEPARATOR,$path);
$path = str_replace('\t3'.'',DIRECTORY_SEPARATOR,$path);
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!