Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results
/*
* ChainableClass
* cascading-by-chaining by returning this
*/
class ChainableClass {
function methodOne() {
echo __METHOD__.' called, ';
return $this;
}
function methodTwo() {
echo __METHOD__.' called';
return $this;
}
}
(new ChainableClass)->methodOne()->methodTwo();
// Result: BaseClass::methodOne called, BaseClass::methodTwo called
With Static
/*
* ChainableClass
* cascading-by-chaining by returning self
*/
class ChainableClassStatic {
public static $prop;
public static function ChainableStaticMethod()
{
self::$prop = 'Chainable Class String';
return new self;
}
public function regularMethod()
{
echo self::$prop;
}
}
ChainableClassStatic::ChainableStaticMethod()->regularMethod();
// Result: Chainable Class String