TalkPHP
 
 
Account Login
Latest Articles
» cURL Basics
» Securing your PHP applications Part 1
» The way the function rolls
» Database Abstraction with Zend_Db - Part 2
» CSRF POST Token Protection
Advertisement
Associates
Associates
techtuts Darkmindz
CSS Tutorials Tutorialsphere.com - Free Online Tutorials
Boston PHP SurfnLearn
Reply
 
LinkBack (3) Thread Tools Display Modes
Old 09-18-2007, 01:14 PM   3 links from elsewhere to this Post. Click to view. #1 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 613
Thanks: 2
Salathe is on a distinguished road
Default 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.
Salathe is offline  
Reply With Quote
The Following User Says Thank You to Salathe For This Useful Post:
Andrew (01-01-2008)
Old 10-01-2007, 11:06 AM   #2 (permalink)
The Gregarious
Upcoming Programmer Inquisitive 
 
Join Date: Sep 2007
Posts: 508
Thanks: 57
Tanax is on a distinguished road
Default

And this would be useful because..? :P
Tanax is offline  
Reply With Quote
Old 10-01-2007, 11:24 AM   #3 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 429
Thanks: 22
Karl is on a distinguished road
Default

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.
Karl is offline  
Reply With Quote
Old 10-23-2007, 11:25 AM   #4 (permalink)
The Visitor
 
Acrylic's Avatar
 
Join Date: Sep 2007
Location: Rochester, NY
Posts: 4
Thanks: 0
Acrylic is on a distinguished road
Default

Wow! Thanks for this it will come in handy. :)
Acrylic is offline  
Reply With Quote
Old 11-13-2007, 05:56 PM   #5 (permalink)
The Contributor
 
Join Date: Nov 2007
Location: California
Posts: 49
Thanks: 0
dschreck is on a distinguished road
Default 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.
dschreck is offline  
Reply With Quote
Old 11-15-2007, 11:13 AM   #6 (permalink)
The Contributor
 
Join Date: Nov 2007
Posts: 32
Thanks: 5
Morishani is on a distinguished road
Default

Thanks! Very useful :)
Send a message via ICQ to Morishani Send a message via MSN to Morishani
Morishani is offline  
Reply With Quote
Reply


LinkBacks (?)
LinkBack to this Thread: http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html
Posted By For Type Date
Quick Web Source - advanced php - php5's oop method chaining This thread Refback 01-14-2008 11:13 PM
OOP PHP - php-brasil | Grupos do Google This thread Refback 12-27-2007 10:09 AM
OOP PHP - php-brasil | Grupos do Google This thread Refback 12-24-2007 09:36 AM

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 05:35 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0