2013-01-21 95 views
3

我正在测试写js的PHP的方式,我不知道这是否可能。PHP,返回类作为对象

如果说我有A,B功能的C类

Class C{ 
    function A(){ 

    } 
    function B(){ 

    } 
} 
$D = new C; 

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

在JS,我们可以简单的写like D.A().B();

我试过return $thisfunction A(),没有工作里面。

非常感谢您的建议。

回答

7

你在找什么叫做流利的界面。您可以通过实现它的类方法返回自己:

Class C{ 
    function A(){ 
     return $this; 
    } 
    function B(){ 
     return $this; 
    } 
} 
+0

非常感谢您! – Till

6

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

+0

非常感谢!我发现我写错了一些东西......我不好意思发表这个问题.. – Till

3

其实很简单,你有一系列的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不会其他的功能。

2

我想它和它的工作

<?php 

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

$c = new C(); 
$c->a()->b(); 
?>