3

I am testing the way writing PHP like js, and I wonder if this will be possible.

If say I have A, B function in Class 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 D.A().B();

I tried return $this inside of function A(), didnt work.

Thank you very much for your advice.

4 Answers 4

11

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;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

9

Returning $this inside the method A() is actually the way to go. Please show us the code that supposedly didn't work (there probably was another error in that code).

1 Comment

Thank you very much!, and I found that I write something wrong...my bad to post the question..
5

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.

<?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 the function allows you to call the other function with the same object just like jQuery does.

Comments

2

I tried it and it worked

<?php

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.