₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,325,084 members, 8,420,240 topics. Date: Thursday, 04 June 2026 at 02:24 PM

Toggle theme

Chaining In Php - Webmasters - Nairaland

Nairaland ForumScience/TechnologyWebmastersChaining In Php (822 Views)

1 Reply

Chaining In Php by cdeveloper(op): 2:58pm On Mar 09, 2010
I have been a fan of the ability to achieve chaining in Javascript as demonstrated by the famous javascript library jQuery with its philosophy of Code less Do More after grappling around this idea for a while i started thinking about the possibility of bringing it to php and somehow i have seen that even php has that ability to achieve chaining too but i am yet to explore the possible application of this concept. though one area i am looking at is web services.This is how i was able to do it. I may have to look for a more viable application of this


/* Sample beta class */

class Beta
{
  private $firstname;
  private $surname;
  private $aga;

public function __construct($age=0)
{
   $this->firstname='Cdeveloper';
   $this->surname='Ama';
   $this->age=$age;
}

/* A method to set a new name */
public function setFirstname($fname='')
{
     $this->firstname=$fname;
     return $this;
}
/* A method to set surname */
public function setSurname($sname='')
{
   $this->surname=$sname;
   return $this;
}
/* a method to set a new age*/
public function setAge($age=0)
{
    $this->age=$age;
    return $this;
}
/* a method to get fullname */
public function getName()
{
  return ucfirst(strtolower($this->firstname))." ".ucfirst(strtolower($this->surname));
}

}

Now to see the chaining thing in action i will create an instance of the class

$beta=new Beta(20);
//get the current default fulllname
echo $beta->getName() ;
Output: Cdeveloper Ama
//to set a new name and output it
echo $beta->setFirstname("Dummy"wink->setSurname("Don"wink->getName();
Output: Dummy Don
/* to set firstname, age,surname and out put them*/
echo $beta->setFirstname("Dummy"wink->setSurname("Don"wink->setAge(30)->getName();



This is really funny but a viable idea that can be used in building api that people can use much in the same way that jQuery is used.
The secret is in returning $this in the setters methods. This variable is internally an instance of the class itself and when you return it from
the method it allows you to still call other methods associated with the object. This is one place that Javascript is king,and this is the concept
that makes jQuery standout. with one line of code you can do more
House what do you guys make of this?
1 Reply

A Beginners Guide To Object-oriented Programming (OOP) In PHP 5+Ecommerce Web Application Written From Scratch In Php For Sale With Mobile ViewWhat's The Difference Between "require Once" And "include" In Php?234

How Do U Get Cusomised Sms Code With Gsm Operators For My App?Xnaira.com For SaleHow To Make Your Site Accepted By Most People