3

我正在测试像 js 一样编写 PHP 的方式,我想知道这是否可能。

如果说我在 C 类中有 A、B 功能。

Class C{
   function A(){

   }
   function B(){

   }
}
$D = new C;

$D->A()->B(); // <- Is this possible and how??

在 Js 中,我们可以简单地写like D.A().B();

return $this我在里面试过function A(),没用。

非常感谢您的建议。

4

4 回答 4

9

您正在寻找的是所谓的流畅界面。你可以通过让你的类方法返回自己来实现它:

Class C{
   function A(){
        return $this;
   }
   function B(){
        return $this;
   }
}
于 2013-01-21T09:17:19.257 回答
8

返回$this方法内部A()实际上是要走的路。请向我们展示据称不起作用的代码(该代码中可能存在另一个错误)。

于 2013-01-21T09:17:26.553 回答
4

它真的很简单,你有一系列的 mutator 方法,它们都返回原始(或其他)对象,这样你就可以继续调用函数。

<?php
class fakeString
{
    private $str;
    function __construct()
    {
        $this->str = "";
    }

    function addA()
    {
        $this->str .= "a";
        return $this;
    }

    function addB()
    {
        $this->str .= "b";
        return $this;
    }

    function getStr()
    {
        return $this->str;
    }
}


$a = new fakeString();


echo $a->addA()->addB()->getStr();

这输出“ab”

在函数内部返回$this允许您使用相同的对象调用另一个函数,就像 jQuery 一样。

于 2013-01-21T09:17:39.317 回答
2

我试过了,它奏效了

<?php

class C
{
  public function a() { return $this; }
  public function b(){ }
}

$c = new C();
$c->a()->b();
?>
于 2013-01-21T09:20:36.587 回答