john denver Contaoi john denver Contaoi - 3 months ago 7
PHP Question

PHP OOP about class

Hi I want to make a code like this... Can you give me an example on how to implement this?

$theclassvariable = new Myclass();
$theclassvariable->firstMethod()->secondMethod($param,$param);


Thank you so much.

Answer

It is called chainable methods. In order to apply a method on $theclassvariable it needs to be an instance of a class. Let's define it:

class myClass {

    public function __construct()
    {
      echo 'a new instance has been created!<br />';
    }

    public function firstMethod()
    {
      echo 'hey there that\'s the first method!<br />';
      return $this;
    }

    public function secondMethod($first, $second)
    {
      echo $first + $second;
      return $this;
    }
}

$theclassvariable = new myClass();

If you want to apply a method on another method $theclassvariable->firstMethod->secondMethod(), $theclassvariable->->firstMethod needs to be an object too. In order to do that you need to return $this (the object in each method). That's how you create chainable methods in PHP (and other languages...).

$theclassvariable->firstMethod()->secondMethod(1, 1);

The above will echo:

a new instance has been created!
hey there that\'s the first method!
2
Comments