【问题标题】:PHP Link Object Operator functions within class类中的 PHP 链接对象运算符函数
【发布时间】:2014-03-11 18:57:23
【问题描述】:

尝试学习 OO PHP,但我对某些事情感到困惑。在将 -> 链接在一起之前,我使用过框架来调用这些函数中的多个函数或变量。

ex. $variable = $this->query($stmt)->result()->name;

您将如何进行设置?

class test{
    public $name;
    public function __construct(){      
        $this->name = 'Jon'; // pretending that Jon is a db call result
    }
    public function change_name($n){
        $this->name = $n; 
    }
    public function get_name(){
        return $this->name;
    }
}
$i = new test();

我该怎么做?或者这完全不可能。

$i->change_name('george')->get_name; // as an example

【问题讨论】:

标签: php


【解决方案1】:

当您说“链接”时,您真正的意思是“链接”

在你的例子中 $i->change_name('george')->get_name; // 举例

(!)你有两个错误

1) ->get_name 应该是 ->get_name() ; // 它是一个函数而不是一个属性

2) 即使使用 ->get_name(),它也不起作用,因为它没有上下文。

举例:

当你这样做时: $i->change_name('george') // 方法 change_name() 有上下文 $i

我们继续:

$i->change_name('george')->get_name() // the method get_name() have the context returned by change name, in your case its nothing because your function change_name return nothing 

如果我们查看您的 change_name 正文:

public function change_name($n){
    $this->name = $n; 
}

不返回任何内容,这意味着如果您愿意,此函数返回 void 或不返回任何内容。

在您的情况下,您想要返回对象上下文,即“$this”

尝试:

public function change_name($n){
    $this->name = $n;
    return $this; 
}

当你会做的时候做:

$i->change_name('george')->get_name() // 方法 change_name() 有 change name 返回的上下文,现在可以工作了

【讨论】:

  • 不错的评论。谢谢!
【解决方案2】:

change_name()返回$this

public function change_name($n){
    $this->name = $n; 
    return $this;
}

【讨论】:

    【解决方案3】:

    这称为方法链接。你可以实现它:

    我推荐你到这个链接:

    PHP method chaining?

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多