
Chaining PHP Methods
Many frameworks these days allow for elegant 'chaining' of methods. This typically looks similar to $this->db->get()->users(); Want to know how to do this? we will show you how in the steps below.
Final Result
<?php class Shape { /** * Name. * * @var string */ public $name = 'square'; /** * Color. * * @var string */ public $color = 'black'; /** * Width in pixels. * * @var int */ public $width = 0; /** * Height in pixels. * * @var int */ public $height = 0; /** * Set the shape name. * * @param string $name */ public function setName($name) { $this->name = $name; return $this; } /** * Set the shape color. * * @param string $color */ public function setColor($color) { $this->color = $color; return $this; } /** * Set the shape dimensions. * * @param int $width * * @param int $height */ public function setDimensions($width, $height) { $this->width = $width; $this->height = $height; return $this; } /** * Display our object. */ public function display() { echo @<<Name: {$this->name}
Color: {$this->color}
Dimensions: {$this->width}px x {$this->height}px DISPLAY; } } $rectangle = new Shape(); $rectangle->setName('rectangle')->setColor('red')->setDimensions(100, 500)->display(); ?>
First off we simply set the default values for a generic shape object. Then we provide several methods such as the one below, which simply assign a variable to the corresponding property. This could be done with public properties such as $rectangle->name = 'rectangle'. However this is to demonstrate chainable methods. Each method which is mutative (modifies the object), and which does not need to return a specific value, could potentially be chainable, simply by returning its-self (return $this).
<?php public function setName($name) { $this->name = $name; return $this; } ?>
We then need a quick method to display our object. the '@<<<' syntax below may look intimidating, this is called heredoc, which is comparable to a simple string using double quotes "". The '@' character suppresses notices if a variable is not present such as if I were to try and output $this->nothingHere. '<<