【问题标题】:php function calls with and without brackets带和不带括号的php函数调用
【发布时间】:2016-11-01 12:33:54
【问题描述】:
在 laravel 中使用关系时,可以调用带或不带括号的关系函数:
public function posts()
{
return $this->hasMany('Post');
}
$user->posts();
$user->posts;
第一次调用将返回查询构建器的实例,第二次调用将返回所有帖子的数组。
这个功能是怎么做的?
【问题讨论】:
标签:
php
function
laravel
class
【解决方案1】:
这是通过实现__get魔术方法来完成的:
class User {
private $posts = [1, 2, 3];
public function __get($key) {
if ($key === 'posts')
return $this->$key;
}
public function posts() {
return count($this->posts);
}
}
$u = new User;
var_dump($u->posts());
var_dump($u->posts);
输出
int(3)
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}