简体   繁体   English

PHP,返回类作为对象

[英]PHP, return class as object

I am testing the way writing PHP like js, and I wonder if this will be possible. 我正在测试像js一样编写PHP的方式,我想知道这是否可行。

If say I have A, B function in Class C. 如果说我有A,B在C类中起作用。

Class C{
   function A(){

   }
   function B(){

   }
}
$D = new C;

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

In Js, we can simple write like DA().B(); 在Js中,我们可以简单地写成like DA().B();

I tried return $this inside of function A() , didnt work. 我试过在function A() return $this ,没有用。

Thank you very much for your advice. 非常感谢您的建议。

What you are looking for is called fluent interface. 您正在寻找的是一个流畅的界面。 You can implement it by making your class methods return themselves: 您可以通过使类方法返回来实现它:

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

Returning $this inside the method A() is actually the way to go. 在方法A()返回$this实际上是要走的路。 Please show us the code that supposedly didn't work (there probably was another error in that code). 请告诉我们那些据说不起作用的代码(该代码可能还有其他错误)。

Its rather simple really, you have a series of mutator methods that all returns the original (or other) objects, that way you can keep calling functions. 它真的很简单,你有一系列的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();

This outputs "ab" 输出“ab”

Returning $this inside the function allows you to call the other function with the same object just like jQuery does. 在函数内部返回$this允许您像jQuery一样使用相同的对象调用另一个函数。

I tried it and it worked 我尝试了它,它的工作原理

<?php

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM