Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Method chaining in php5

Status
Not open for further replies.

jpadie

Technical User
Nov 24, 2003
10,094
FR
I don't know why I didn't think of this years ago but it is possible to method chain in php5. not just between subsidiary objects but within the same object.

in case it's useful for anyone consider this

Code:
<?php 

class example{
	
	public $name;
	public $address;
	public $telephone;
	public $email;
	
	public function __call($name, $value){
		if (substr(strtolower($name), 0, 3) == 'set'){
			$property = substr($name,3);
			if ($this->isProperty($property)){
				$this->$property  = $value[0];
				[red]return $this;[/red]
			}
		}
	}
	private function isProperty($property){
		$vars = array_map('strtolower', array_keys(get_object_vars($this)));
		return (in_array(strtolower($property), $vars));
	}
	
	public function output(){
		echo "<pre>" . print_r($this, true);
	}
}

$e = new example;
$e	->setname('Justin')
	->setaddress('my address')
	->settelephone('020 1234 5678')
	->setemail('myemail@mydomain.com')
	->output();
?>

the key bit is for your method to return an instance of its containing object.

the above code uses method overloading to create a method of setting properties. there are better ways to do this but the point of this code was to show how to chain methods rather than anything else.
 
Agree that this is useful to know and would like to add that method chaining can make code more compact and robust. As a simple example:

Code:
$object->methodA()->methodB();

The key is to return $this from methods "methodA" and "methodB". Any method that returns the object is suitable for chaining.


Steven Parker
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top