Home > database >  How do I pass function return value with other functions like that in php?
How do I pass function return value with other functions like that in php?

Time:02-20

I want to access php function like below. I've a php class and it has some properties and methods. But I want to access those method with arrow function. Like funcA()->funcB(); Please check the below code for reference [Note: I don't know the Technic name. So I can't search it on google :(]

class myClass{

    # PROPERITES
    private $var1;
    private $var2;

    # FUNCTION A
    public function FuncA($number)
    {
      // Get the value & set into property
      $this->var1 = $number;
    }

    # FUNCTION B
    private function FuncB()
    {
      // Do process & Set value into property for other uses
      $this->var2 = $this->var1   10;
   }

   # FUNCTION C
   public function FuncC()
   {
     // Show result
     return $this->var2;
   }
}

Now I want to access this class and function like that

$ob = new myClass();
$ob->FuncA(10)->FuncC();

CodePudding user response:

It's called "method chaining" and to be able to do that, you need to return the instance.

class Foo
{
    public function methodA()
    {
       // do stuff

       // Return the current class instance    
       return $this;
    }

    public function methodB()
    {
       // do stuff
    
       // Return the current class instance    
       return $this;
    }

    public function methodC()
    {
       // Return a value
       return $this->something;
    }
}

Now you can call them like this:

$foo = new Foo;

$val = $foo->methodA()->methodB()->methodC();

Note that you can only do this for methods that return $this, so in this example, you need to call methodC() last.

  • Related