[Solved] PHP OOP about class


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

2

solved PHP OOP about class