 |
Account Login
|
 |
 |
Latest Articles
|
 |
 |
IRC Channel
|
 |
 |
Associates
|
 |
 |
Associates
|
 |
|
 |
|
 |
|
 |
09-18-2007, 01:14 PM
|
#1 (permalink)
|
|
Moderateur
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
|
PHP5 Method Chaining
Introduction
In this article, I'll be talking about a useful new feature introduced in PHP5 as part of the OOP improvements over PHP4. This feature is called Method Chaining and enables us to do pretty cool things like:
PHP Code:
$object->method_a()->method_b()->method_c();
So really what's this all about? Well, one change (of many) between PHP4 and PHP5 is that now methods can return objects. That's only a small change but allows for a new way of thinking about how you handle objects and their methods.
In order to be able to chain methods together, as mentioned earlier, you need to be able to return an object. The returned object does not necessarily need be the same one from which the method is being called, but we'll not be touching on that fact in this article. Let's go for a quick illustration of how to put all of this into action.
Regular Use of a Class
We'll start off with a basic class, which doesn't do anything particularly interesting but it will serve our purpose.
PHP Code:
// This Person class encapsulates a couple of properties which // a person might have: their name and age. // We also give the Person the opportunity to introduce themselves. class Person { private $m_szName; private $m_iAge; public function setName($szName) { $this->m_szName = $szName; } public function setAge($iAge) { $this->m_iAge = $iAge; } public function introduce() { printf( 'Hello my name is %s and I am %d years old.', $this->m_szName, $this->m_iAge); } }
Now, we can create a new Person (see example below) and give them a name and age. Using the introduce method, the person can them introduce themselves.
PHP Code:
// We'll be creating me, digitally. $peter = new Person();
// Let's set some attributes and let me introduce myself. $peter->setName('Peter'); $peter->setAge(23); $peter->introduce();
The above example would output: Hello my name is Peter and I am 23 years old.
Implementing Method Chaining
Great, but you already knew how to do that didn't you! In actuality, we only need to add two lines of code to the basic class above to enable us to write a chain, and the second line is a repeat of the first! How's it done? Quite simply we need to return the Person object from each method. At the moment, none of the methods actually return anything so we'll amend that now. We just need to add return $this; to the methods setName and setAge.
The amended Person class is as follows:
PHP Code:
// This Person class encapsulates a couple of properties which // a person might have: their name and age. // We also give the Person the opportunity to introduce themselves. class Person { private $m_szName; private $m_iAge; public function setName($szName) { $this->m_szName = $szName; return $this; // We now return $this (the Person) } public function setAge($iAge) { $this->m_iAge = $iAge; return $this; // Again, return our Person } public function introduce() { printf( 'Hello my name is %s and I am %d years old.', $this->m_szName, $this->m_iAge); } }
Ok, is that it? Yep, really. Because we return the Person from those methods, it enables us to group method calls together in a sequence, or chain. I'll re-do the previous example but this time using our new magical chaining abilities.
PHP Code:
// We'll be creating me, digitally. $peter = new Person();
// Let's set some attributes and let me introduce myself, // all in one line of code. $peter->setName('Peter')->setAge(23)->introduce();
That example will produce exactly the same output as our regular, boring example earlier! All because we return the Person object in the setName/Age methods.
How does that work?
If you're a bit confused about precisely what is going on here, let me try to walk you through the process, step by step. We'll go through the line of code as it is processed, from left to right.
First up is $peter->setName('Peter'). This assigns the person's name to be Peter, my name and returns $this -- that is, the $peter object. So at the moment Peter has his name, but no age!
Next up comes ->setAge(23). Because we're chained with the previous method, PHP interprets the code and says "execute the setAge method belonging to whatever was returned from the previous method." In this case, PHP executes the setAge method belonging to our Person object, $peter.
The exact same thing happens when we finally call the introduce method. PHP executes the introduce method belonging to whatever was returned from the setAge method call: $peter.
Hopefully, that's at least a bit clear and I'll let you mull over this confusing (until you get it) subject for a while. I'll leave you with the note that because we can chain methods, they can be called more than once and in whatever order we like which could lead to the amazingly useless snippet below:
PHP Code:
// Hello my name is Winifred and I am 72 years old. $peter->setAge(23) ->setName('Peter') ->setName('Winifred') ->setAge(72) ->introduce();
In Conclusion
We can boil this whole article down into one short sentence. If you return $this then you can chain the method calls together. Done. :)
Last edited by Salathe : 09-19-2007 at 08:33 PM.
|
|
|
|
|
The Following 6 Users Say Thank You to Salathe For This Useful Post:
|
|
10-01-2007, 11:06 AM
|
#2 (permalink)
|
|
The Prestige
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
|
And this would be useful because..? :P
|
|
|
|
10-01-2007, 11:24 AM
|
#3 (permalink)
|
|
The Reckoner
Join Date: Sep 2007
Posts: 437
Thanks: 22
|
Readability and reduction of code repeation. Consider the following example I use in my library:
PHP Code:
$aMembers = $this->m_pMembers ->join('jobs') ->join('orders') ->fetchAll($szFields, $szConditions);
The same code could be written like this, without method chaining:
PHP Code:
$this->m_pMembers->join('jobs'); $this->m_pMembers->join('orders'); $aMembers = $this->m_pMembers->fetchAll($szFields, $szConditions);
Admitidly, we've actually added an extra line of code using method chiaining, but we've reduced the amount of code written, removed duplicate code and made it much easier to read. It's all a matter of preference in all honesty, there is no clear cut advantage (that I personally know of, can anyone give me one?) of using method chaining, it's simply a OOP feature that can be used to help improve your code.
|
|
|
|
|
The Following 2 Users Say Thank You to Karl For This Useful Post:
|
|
10-23-2007, 11:25 AM
|
#4 (permalink)
|
|
The Wanderer
Join Date: Sep 2007
Location: Rochester, NY
Posts: 6
Thanks: 1
|
Wow! Thanks for this it will come in handy. :)
|
|
|
|
11-13-2007, 06:56 PM
|
#5 (permalink)
|
|
The Contributor
Join Date: Nov 2007
Location: California
Posts: 82
Thanks: 0
|
good tutorial
good write up, needed to explain this to some JR's, googled it, and found this here. Good job explaining this very usable and convenient pattern.
so, kudos for you.
|
|
|
|
11-15-2007, 12:13 PM
|
#6 (permalink)
|
|
The Contributor
Join Date: Nov 2007
Posts: 32
Thanks: 5
|
Thanks! Very useful :)
|
|
|
10-28-2008, 02:55 PM
|
#7 (permalink)
|
|
The Wanderer
Join Date: Oct 2008
Location: Brazil, Balneário Camboriu
Posts: 6
Thanks: 1
|
Hum, pretty good! I was just thinking about it and found that this is very great a progress to PHP language, because, as you must know most languages, both scripting or not have method chaining somehow, to webdevelopers it would be pretty nice for PHP allow method chaining, in fact we generally deal with Javascript often, and as you know too, string.value.length is now possible in php as string()->value()->length().
Great post, thanks again!
|
|
|
11-28-2008, 02:07 AM
|
#8 (permalink)
|
|
The Visitor
Join Date: Nov 2008
Posts: 3
Thanks: 0
|
Doh!
I've been writing chaining in JavaScript with exactly this same approach for close to a year new, wishing that PHP could offer the same functionality.
Then it occurs to me... hey, I never googled it. I google it, and this is the first thing I find.
I had completely missed that we can now return objects. That changes everything.
|
|
|
|
11-28-2008, 02:25 AM
|
#9 (permalink)
|
|
La Vida es Sueño
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
|
Lol  Such a good find, I imagine! Welcome to the community as well, my friend!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
|
|
|
11-28-2008, 05:17 AM
|
#10 (permalink)
|
|
The Addict
Join Date: Apr 2008
Posts: 200
Thanks: 18
|
well, as i study some of the articles regarding classes, i have read about this technique wherein you return the object so that you can do the chain.
e.g
the object is the cat then we apply some color on it. Yellow after which return the object again, so we can again apply any other property on it.
Cat(object)->yellow(color)->Cat(returned object)->etc..
so any instances if we apply it to classes we can do the chain as what discuss above.(if im not mistaken about it)
PHP Code:
$obj = new object(); $obj->setname(params)->setcolor(params)->setsize(params)->etc..
Thanks for the share, atleast we also have a detail discussion about it too :)
|
|
|
|
11-28-2008, 12:38 PM
|
#11 (permalink)
|
|
The Wanderer
Join Date: Oct 2008
Location: Brazil, Balneário Camboriu
Posts: 6
Thanks: 1
|
Quote:
Originally Posted by exquisiteoath
I've been writing chaining in JavaScript....
|
Sure! This is fantastic!
__________________
...it's about producing and sharing!
|
|
|
12-20-2009, 03:26 AM
|
#12 (permalink)
|
|
The Wanderer
Join Date: Aug 2009
Posts: 18
Thanks: 1
|
Nice, but...
Isn't there like a way where you can use these both separate? , I tried these:
...*removed*
Okay I made a little solution for the selecting weather to chain your class or not, it's fussy though, but it helps I guess  :
PHP Code:
<?php // December 19 2009 [10:02 a.m. MS]
class person { private $name; private $age; private $chain; // want to chain? false (/no) by default function __construct($chain=false) { $this->chain = $chain; if($this->chain == false) { // Set to false by default return false; } else { return true; } } public function set_name($name) { if($this->chain == false) { return $this->name = $name; } else { $this->name = $name; return $this; } } public function set_age($age) { if($this->chain == false) { return $this->age = $age; } else { $this->age = $age; return $this; } } public function introduce() { if(empty($this->name)) { print("I need a name!"); } else if(empty($this->age)) { print("I dont have an age!"); } else { printf("Hello there, my name is <b>%s</b> and I am <b>%s</b> years old.", $this->name, $this->age); } } }
$person = new person(); $name = "Jarod"; $age = 17; echo "Normal Method"; echo "<br />"; echo $person->set_name($name) . "<br />"; echo $person->set_age($age) . "<br />"; $person->introduce(); echo "<br />"; echo "<br />"; echo "<br />"; echo "Chaining Method"; echo "<br />"; $person = new person(true); // chaining method $person->set_name($name)->set_age($age)->introduce();
/** OUTPUT::>> * Normal Method * Jarod * 17 * Hello there, my name is Jarod and I am 17 years old. * * * Chaining Method * Hello there, my name is Jarod and I am 17 years old. */ ?>
Last edited by Jarod B : 12-20-2009 at 04:06 AM.
|
|
|
|
12-20-2009, 11:54 AM
|
#13 (permalink)
|
|
Moderateur
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
|
Hi Jarod, a better option (in my opinion) would be to make use of the class hierarchy rather than doing everything in one class.
E.g. (just snippets)
PHP Code:
class Person {
protected $name;
public function set_name($name) {
return $this->name = $name;
}
}
class ChainablePerson extends Person {
public function set_name($name) {
parent::set_name($name);
return $this;
}
}
|
|
|
|
12-20-2009, 11:15 PM
|
#14 (permalink)
|
|
The Wanderer
Join Date: Aug 2009
Posts: 18
Thanks: 1
|
Not Bad
I guess, but they seem to be the same way to me if you think about it, just in another class  .
|
|
|
|
12-24-2009, 06:54 AM
|
#15 (permalink)
|
|
The Contributor
Join Date: Feb 2007
Posts: 64
Thanks: 9
|
Awesome. I recently learned of method chaining by playing with Kohana and thought you needed to do this with factory. Continuing to learn... it's nice :D
|
|
|
|
12-24-2009, 11:04 PM
|
#16 (permalink)
|
|
The Wanderer
Join Date: Aug 2009
Posts: 18
Thanks: 1
|
Can you explain to be what Kohana your talking about (I dont know either really)? lol
|
|
|
|
12-25-2009, 06:38 AM
|
#17 (permalink)
|
|
The Contributor
Join Date: Feb 2007
Posts: 64
Thanks: 9
|
Quote:
Originally Posted by Jarod B
Can you explain to be what Kohana your talking about (I dont know either really)? lol
|
Kohana is a framework, see kohanaphp.com.
|
|
|
|
10-18-2012, 12:39 PM
|
#18 (permalink)
|
|
The Addict
Join Date: Oct 2012
Posts: 244
Thanks: 0
|
Some conservatives have Coach Factory Outlet pushed that critique further, saying that Mr. Obama’s policies are too costly, often assist the wrong people Louis Vuitton Belts and could have the paradoxical effect of driving up college costs. The dispute turns not just on different Coach Factory Outlet assessments of how policies play out, but on differing philosophical views about the role of government. During Gucci Belts his time in office, Mr. Obama has sharply increased aid to low- and middle-income students, notably through the Pell Grant Coach Factory Outlet program, which grew from $14.6 billion given to 6 million students in 2008, to nearly $40 billion for Coach Factory Outlet almost 10 million students this year. His administration also made it easier to request aid, shortening the Coach Factory Online complex federal application and allowing people to transfer their financial information electronically from the Internal Coach Outlet Online Revenue Service database. But while many education experts laud his efforts, analysts of varying political Coach Outlet Online stripes have also questioned how much impact some of the president’s policies will have, noting that the prices Coach Online Outlet charged by colleges, and student borrowing, continue to climb.But behind the headlines about soaring costs, the Coach Factory Outlet Online reality is more complex and wildly uneven, because a growing number of students receive Coach Outlet Online financial aid, and only relatively high-income families pay those fast-rising sticker prices. Adjusted for Coach Factory Online inflation, the College Board calculates, the average net price changed little over the last decade at private Coach Factory Outlet schools, and rose only modestly at public ones.Defending federal spending, Arne Duncan, the secretary of Hermes Belts education, said that for more than 30 years, college prices had risen even when federal aid had not, leading him to believe Coach Factory Online there was zero correlation.
|
|
|
|
10-22-2012, 09:16 AM
|
#19 (permalink)
|
|
The Addict
Join Date: Oct 2012
Posts: 244
Thanks: 0
|
Coach Outlet
You’ve relatively Coach Outlet recently arrived in New Delhi after living in two of Asia’s other great cities, Coach Outlet Store Online Tokyo and Hong Kong, for several years. Do these cities feel like they’re part of the same continent? Yes, and no. In terms Coach Factory Onlineof infrastructure, they couldn’t be more different. Getting regular Coach Outlet power and water at my house in New Delhi is never a sure thing, even though Coach Purse Outlet OnlineI’m paying the same rent that I paid in Tokyo and almost the same electricity prices. Both Hong Kong and Tokyo are also crowded places, Coach Factory Outlet Online but both cities are incredibly well planned and efficiently run. Efficient is not a word I would use to describe my Coach Bags Outlet Onlineday-to-day life in New Delhi. On the other hand, one thing that I think Hong Kong and New Delhi have in common is Coach Handbags Outlet a shared sense of optimism — a feeling that the best is yet to come. That’s definitely not the feeling you get in Tokyo, Coach Outlet Online or in the U.S. when I go home. It’s a big part of what I find addictive about living and working in this part of the world. You feel like you’re watching the future unfold.
|
|
|
|
11-01-2012, 07:08 AM
|
#20 (permalink)
|
|
The Wanderer
Join Date: Oct 2012
Posts: 10
Thanks: 0
|
Quote:
Originally Posted by Salathe
Introduction
In this article, I'll be talking about a useful new feature introduced in PHP5 as part of the OOP improvements over PHP4. This feature is called Method Chaining and enables us to do pretty cool things like:
PHP Code:
$object->method_a()->method_b()->method_c();
So really what's this all about? Well, one change (of many) between PHP4 and PHP5 is that now methods can return objects. That's only a small change but allows for a new way of thinking about how you handle objects and their methods.
In order to be able to chain methods together, as mentioned earlier, you need to be able to return an object. The returned object does not necessarily need be the same one from which the method is being called, but we'll not be touching on that fact in this article. Let's go for a quick illustration of how to put all of this into action.
Regular Use of a Class
We'll start off with a basic class, which doesn't do anything particularly interesting but it will serve our purpose.
PHP Code:
// This Person class encapsulates a couple of properties which // a person might have: their name and age. // We also give the Person the opportunity to introduce themselves. class Person { private $m_szName; private $m_iAge; public function setName($szName) { $this->m_szName = $szName; } public function setAge($iAge) { $this->m_iAge = $iAge; } public function introduce() { printf( 'Hello my name is %s and I am %d years old.', $this->m_szName, $this->m_iAge); } }
Now, we can create a new Person (see example below) and give them a name and age. Using the introduce method, the person can them introduce themselves.
PHP Code:
// We'll be creating me, digitally. $peter = new Person();
// Let's set some attributes and let me introduce myself. $peter->setName('Peter'); $peter->setAge(23); $peter->introduce();
The above example would output: Hello my name is Peter and I am 23 years old.
Implementing Method Chaining
Great, but you already knew how to do that didn't you! In actuality, we only need to add two lines of code to the basic class above to enable us to write a chain, and the second line is a repeat of the first! How's it done? Quite simply we need to return the Person object from each method. At the moment, none of the methods actually return anything so we'll amend that now. We just need to add return $this; to the methods setName and setAge.
The amended Person class is as follows:
PHP Code:
// This Person class encapsulates a couple of properties which // a person might have: their name and age. // We also give the Person the opportunity to introduce themselves. class Person { private $m_szName; private $m_iAge; public function setName($szName) { $this->m_szName = $szName; return $this; // We now return $this (the Person) } public function setAge($iAge) { $this->m_iAge = $iAge; return $this; // Again, return our Person } public function introduce() { printf( 'Hello my name is %s and I am %d years old.', $this->m_szName, $this->m_iAge); } }
Ok, is that it? Yep, really. Because we return the Person from those methods, it enables us to group method calls together in a sequence, or chain. I'll re-do the previous example but this time using our new magical chaining abilities.
PHP Code:
// We'll be creating me, digitally. $peter = new Person();
// Let's set some attributes and let me introduce myself, // all in one line of code. $peter->setName('Peter')->setAge(23)->introduce();
That example will produce exactly the same output as our regular, boring example earlier! All because we return the Person object in the setName/Age methods.
How does that work?
If you're a bit confused about precisely what is going on here, let me try to walk you through the process, step by step. We'll go through the line of code as it is processed, from left to right.
First up is $peter->setName('Peter'). This assigns the person's name to be Peter, my name and returns $this -- that is, the $peter object. So at the moment Peter has his name, but no age!
Next up comes ->setAge(23). Because we're chained with the previous method, PHP interprets the code and says "execute the setAge method belonging to whatever was returned from the previous method." In this case, PHP executes the setAge method belonging to our Person object, $peter.
The exact same thing happens when we finally call the introduce method. PHP executes the introduce method belonging to whatever was returned from the setAge method call: $peter.
Hopefully, that's at least a bit clear and I'll let you mull over this confusing (until you get it) subject for a while. I'll leave you with the note that because we can chain methods, they can be called more than once and in whatever order we like which could lead to the amazingly useless snippet below:
PHP Code:
// Hello my name is Winifred and I am 72 years old. $peter->setAge(23) ->setName('Peter') ->setName('Winifred') ->setAge(72) ->introduce();
In Conclusion
We can boil this whole article down into one short sentence. If you return $this then you can chain the method calls together. Done. :)
|
You have shared great article for the PHP updating information which will best helpful to PHP developer and also me. Keep it up.
php web application development | PHP development | php mysql development | cakephp developers
|
|
|
|
|
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
|
|
|
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|