jcadima
7/27/2017 - 4:53 PM

Chaining Methods and Properties

Chaining Methods and Properties


<?php

/*
============  CHAINING METHODS AND PROPERTIES =============

In order to perform chaining the methods should return the $this keyword
this returns the object, we use $this because we are inside the class 
*/
class Car {
	
	public $tank;
	
	public function fill ( $float ) {
		$this->tank += $float;
		return $this;  // return the object
	}
	
	public function ride ( $float ) {
		$miles = $float ;
		$gallons = $miles / 50 ;
		$this->tank -= $gallons;
		return $this; // return the object
	}
	
}

$bmw = new Car() ;
// after fill fills the tank with 10 and rides 40 miles, we have $bwm->tank
$tank = $bmw->fill(10)->ride(40)->tank;

echo "The number of gallons left in the tank " . $tank . ' gallons' ; 

echo PHP_EOL ; // EXAMPLE 2 =======================================

class User {
	public $firstName;
	public $lastName;
	
	public function hello() {
		return "hello, " . $this->firstName;
	}
	
	public function register() {
		echo $this->firstName . ' ' . $this->lastname . " has registered, " ;
		return $this ;
	}
	
	public function mail() {
		echo "emailed" ;
		return $this;
	}
}

$user = new User() ;
$user->firstName = 'Jane' ;
$user->lastname = 'Roe' ;

$user->register()->mail(); 

/*
Note that each method we want to chain to, should return the $this keyword.

If we wanted to write something like this:
$user->register()->mail()->hello() ;

this is required:
register()  return $this
mail()      return $this
hello()     not required to return $this

hello() does not require to return the object($this) because it concludes the chain.
*/