In this article I am going to show you a simple but very useful trick while using “this” keyword for method chaining. “this” when use in the class, refer to the same class.
Consider the following example.
class Person {
protected $_name;
protected $_age;
protected $_gender;
public function setName($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
public function setAge ($age) {
$this->_name = $age;
}
public function getAge() {
return $this->_age;
}
public function setGender($gender) {
$this->_gender = $gender;
}
public function getGender() {
return $this->_gender;
}
}
In object oriented programming it’s always a good practice to define getter and setters. In php you can define __set and __get as setters and getter.
To create an object of the above class and define person properties, we will need to write the following code.
$person = new Person();
$person->setName(“person_name”);
$person->setAge(24);
$person->setGender(“male”);
And now If you want to get these values, write
$person->getName();
$person->getAge();
$person->getGender();
Well, if you want to set values using a single statement, you will need a code similar to this.
$this->setName(‘person_name’)->setAge(24)->setGender(“male”);
To achieve this, you will need to write the following statement in all your setters.
public function setName($name) {
$this->_name = $name;
return $this;
}
The only thing we need here is “return $this”. This statement return a reference to the same object.
Place this statement in your setAge() and setGender(), and now you can write
$this->setName(‘person_name’)->setAge(24)->setGender(“male”);
for setting all the three properties.
Any suggestion is welcome. Cheers
What is the memory/processing overhead of passing the object back each setX() call - is it treated specially and passed by reference?
ReplyDeletepublic function setAge ($age) {
ReplyDelete$this->_name = $age;
}
Should be $this->_age = $age;
Nice, I had been following this blog for a jiffy but I didn't become aware of that you guys we're behind it. Some of the crew from there is really remarkable but they are lacking a demo link. More and more interest and involvement would definitely bump up the experience for me and in all probability many others.Baseball Logo Design
ReplyDeleteExcellent read, I just anesthetized this assimilate a aide who was accomplishing a little analysis on this topic.
ReplyDeleteAdvertising agencies in karachi