php函数调用with括号和不带括号

时间:2016-11-01 12:33:54

标签: php function laravel class

在laravel中使用关系时,可以使用或不使用括号来调用关系函数:

public function posts()
{
  return $this->hasMany('Post');
}

$user->posts();
$user->posts;

第一个调用将返回查询构建器的实例,第二个调用将返回所有帖子的数组。

这个功能是如何制作的?

1 个答案:

答案 0 :(得分:2)

通过实施__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)
}
相关问题