laravel aliases别名的原理

在laravel发现有些类可以直接use 类名,就能使用了,例如use DB;就可以使用DB类了,问题是DB这个类并不在根命名空间,这里面实际就是用到了别名。

先通过如下例子来分析基本原理

建立如下文件upload.php,内容为

<?php
namespace test\test2;
class upload{
	public function test(){
		return 123;
	}
}

2 建立文件index.php,内容为

<?php
namespace b;
require('upload.php');
class_alias ( '\test\test2\upload' , 'upload');
$a=new \upload();
echo $a->test(); 

浏览器执行index.php,成功输出结果123;

可以看到class upload在命名空间test\test2下 但是new upload的时候 并没有new  \test\test2\upload 而是直接new \upload,原因不多说,就是因为函数class_alias导致的.具体的这个函数的用法可以参考手册。这里要补充说明class_alias的第3个参数默认为true,手册上的意思是Whether to autoload if the original class is not found.是什么意思了,还是通过例子说明 ,把index.php修改如下

<?php
namespace b;
//require('upload.php');
spl_autoload_register(fu
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值