PHP, returns class as object

I am testing a way to write PHP as js and I am wondering if this is possible.

If I have a function A, B in class C.

Class C{
   function A(){

   }
   function B(){

   }
}
$D = new C;

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

      

In Js, we can just write like D.A().B();

I tried return $this

inside function A()

, didn't work.

Thanks a lot for your advice.

+3


source to share


4 answers


What you are looking for is called a free interface. You can implement it by making your class methods return:



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

      

+7


source


Returning $this

inside a method A()

is actually the way to go. Please show us a code that supposedly didn't work (there was probably a different bug in that code).



+6


source


Quite simply, you have a series of mutator methods that return the original (or other) objects, so you can keep calling functions.

<?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"

Returning $this

inside a function allows you to call another function with the same object as jQuery.

+3


source


I tried and it worked

<?php

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

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

      

+2


source







All Articles