【问题标题】: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;

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

这个功能是怎么做的?

【问题讨论】:

  • 您可以自己看看。 Laravel 是开源的。

标签: 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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2015-08-25
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 2017-12-27
    相关资源
    最近更新 更多