How do I chain methods in PHP?


The mutator methods can be used to chain methods, wherein these methods return the original objects, and other methods can be called on these objects that are returned by the mutator functions.

Example

Below is a simple example demonstrating the same −

 Live Demo

<?php
class sample_class {
   private $str;
   function __construct() {
      $this->str = "";
   }
   function addA() {
      $this->str .= "am";
      return $this;
   }
   function addB() {
      $this->str .= "_bn";
      return $this;
   }
   function getStr() {
      return $this->str;
   }
}
$new_object = new sample_class();
echo $new_object->addA()->addB()->getStr();

Output

This will produce the following output −

am_bn

Updated on: 06-Apr-2020

984 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements