$this['mailer.username'] 是什么意思?怎么实现的?
重点是那个 $this[]。
这里看到的: segmentfault.com/a/119000001475212... 。
好像是这个:www.php.net/manual/en/class.arraya... ?提交这个问题之后过了几个小时问 ChatGPT 问出来的。不过不太敢信 ChatGPT。大概是只要类实现了那个接口然后 $this 也一样能用那种语法?
问了 ChatGPT 之后几个小时我试了一下,在实现了 ArrayAccess 接口的类的内部不能用类似 $this[‘abc’] 的形式:
<?php
class Test implements ArrayAccess{
function __construct(
private $content = array()
){}
function offsetExists(mixed $offset): bool{
return isset($this->content[$offset]);
}
function offsetGet(mixed $offset): mixed{
return isset($this->content[$offset]) ? $this->content[$offset] : null;
}
function offsetSet(mixed $offset, mixed $value): void{
if (is_null($offset)) {
$this->content[] = $value;
} else {
$this->content[$offset] = $value;
}
}
function offsetUnset(mixed $offset): void{
unset($this->content[$offset]);
}
function thisTest(){
$this['test'] = 123;
}
}
$test = new Test();
$test['abc'] = 1;
echo $test['abc'];
$this->thisTest();
肯定是我搞错了什么吧?
没错,ArrayAccess 是 PHP 预定义 interface,参考 PHP 预定义接口 ArrayAccess
laravel 容器继承 ArrayAccess,源码 Illuminate\Container\Container.php
$app['foo'] = 'bar'
即调用 offsetSet,$app->foo = 'bar'
先调用 __set 再调用 offsetSet 是一个效果。ArrayAccess 应用的很多,还可以参考 laravel 中
config()
函数源码 Illuminate\Config\Repository,其中还包含了$this['mailer.username']
中的.
是怎么实现的,其实就是一个工具类解析