TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack (3) Thread Tools Search this Thread 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: 1,393
Thanks: 5
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 6 Users Say Thank You to Salathe For This Useful Post:
Andrew (01-01-2008), codefreek (10-28-2008), gilbertoalbino (10-28-2008), hello-world (09-17-2009), Runar (11-12-2008), zxt3st (11-28-2008)
Old 10-01-2007, 11:06 AM   #2 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
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: 437
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
The Following 2 Users Say Thank You to Karl For This Useful Post:
codefreek (10-28-2008), Runar (11-12-2008)
Old 10-23-2007, 11:25 AM   #4 (permalink)
The Wanderer
 
Acrylic's Avatar
 
Join Date: Sep 2007
Location: Rochester, NY
Posts: 6
Thanks: 1
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, 06:56 PM   #5 (permalink)
The Contributor
 
dschreck's Avatar
 
Join Date: Nov 2007
Location: California
Posts: 82
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, 12:13 PM   #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
Old 10-28-2008, 02:55 PM   #7 (permalink)
The Wanderer
 
Join Date: Oct 2008
Location: Brazil, Balneário Camboriu
Posts: 6
Thanks: 1
gilbertoalbino is on a distinguished road
Default

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!
Send a message via MSN to gilbertoalbino
gilbertoalbino is offline  
Reply With Quote
Old 11-28-2008, 02:07 AM   #8 (permalink)
The Visitor
 
Join Date: Nov 2008
Posts: 3
Thanks: 0
exquisiteoath is on a distinguished road
Default 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.
exquisiteoath is offline  
Reply With Quote
Old 11-28-2008, 02:25 AM   #9 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

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.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 11-28-2008, 05:17 AM   #10 (permalink)
The Addict
 
zxt3st's Avatar
 
Join Date: Apr 2008
Posts: 200
Thanks: 18
zxt3st is on a distinguished road
Default

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 :)
__________________
Serenity Project - 5% (Layout) - Ongoing....
Project Serenity Free Life!....
zxt3st is offline  
Reply With Quote
Old 11-28-2008, 12:38 PM   #11 (permalink)
The Wanderer
 
Join Date: Oct 2008
Location: Brazil, Balneário Camboriu
Posts: 6
Thanks: 1
gilbertoalbino is on a distinguished road
Default

Quote:
Originally Posted by exquisiteoath View Post
I've been writing chaining in JavaScript....
Sure! This is fantastic!
__________________
...it's about producing and sharing!
Send a message via MSN to gilbertoalbino
gilbertoalbino is offline  
Reply With Quote
Old 12-20-2009, 03:26 AM   #12 (permalink)
The Wanderer
 
Join Date: Aug 2009
Posts: 18
Thanks: 1
Jarod B is on a distinguished road
Default 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.
Jarod B is offline  
Reply With Quote
Old 12-20-2009, 11:54 AM   #13 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

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;
    }

Salathe is offline  
Reply With Quote
Old 12-20-2009, 11:15 PM   #14 (permalink)
The Wanderer
 
Join Date: Aug 2009
Posts: 18
Thanks: 1
Jarod B is on a distinguished road
Default Not Bad

I guess, but they seem to be the same way to me if you think about it, just in another class .
Jarod B is offline  
Reply With Quote
Old 12-24-2009, 06:54 AM   #15 (permalink)
The Contributor
 
Join Date: Feb 2007
Posts: 64
Thanks: 9
Killswitch is on a distinguished road
Default

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
Killswitch is offline  
Reply With Quote
Old 12-24-2009, 11:04 PM   #16 (permalink)
The Wanderer
 
Join Date: Aug 2009
Posts: 18
Thanks: 1
Jarod B is on a distinguished road
Default

Can you explain to be what Kohana your talking about (I dont know either really)? lol
Jarod B is offline  
Reply With Quote
Old 12-25-2009, 06:38 AM   #17 (permalink)
The Contributor
 
Join Date: Feb 2007
Posts: 64
Thanks: 9
Killswitch is on a distinguished road
Default

Quote:
Originally Posted by Jarod B View Post
Can you explain to be what Kohana your talking about (I dont know either really)? lol
Kohana is a framework, see kohanaphp.com.
Killswitch is offline  
Reply With Quote
Old 10-18-2012, 12:39 PM   #18 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

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.
dashixiong is offline  
Reply With Quote
Old 10-22-2012, 09:16 AM   #19 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default Coach Outlet

You’ve relativelyCoach 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 regularCoach 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 isCoach 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.
dashixiong is offline  
Reply With Quote
Old 11-01-2012, 07:08 AM   #20 (permalink)
The Wanderer
 
Join Date: Oct 2012
Posts: 10
Thanks: 0
lennondevid is on a distinguished road
Default

Quote:
Originally Posted by Salathe View Post
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
lennondevid 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-15-2008 12:13 AM
OOP PHP - php-brasil | Grupos do Google This thread Refback 12-27-2007 11:09 AM
OOP PHP - php-brasil | Grupos do Google This thread Refback 12-24-2007 10:36 AM

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
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 08:47 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design