Monday, 26 November 2012

PHP: Cloning and Fluent Interfaces

Cloning
Recently been brushing up on PHP classes and learnt that Objects cannot be directly copied using just the assignment operation, like a variable. Example:
$person1 = new Person("Nick Mok"); //Constructor takes 1 parameter and sets name   
echo $person1->getName(); //Outputs Nick Mok
$person2 = $person1;
$person1->getName(); returns "Nick Mok" as expected. Now on the last line, $person2 actually references $person1. So anything we do to $person2 will happen to $person1. So if we change the name via $person2 variable:
$person2->setName("Fred");
$person1 will be directly affected:
$person1->getName(); //outputs Fred
So how can we copy a variable instead of directly referencing it? We can use the clone keyword
$person1 = new Person("nick mok");
$person2 = clone $person1;
$person2->setName("Johnny");
So now you can do what ever you want with $person2 without affecting $person1.

Fluent Interfaces
Another reminder to me was - when in class context - you can return the $this keyword to achieve fluent interfaces: 

$person1->setName("Nick")->setGender("M")->setCountry("Australia");
Inside each function setName, setGender and setCountry is the setter code and on the last line a return $this statement, example of one:
public function setName($name) {
          $this->name = $name;
          return $this;
}
Returning $this returns the object in context which is $person1, which is an object of Person. using the returned object you can perform another function without having to declare a new line with $this, like so:
$person1->setName("nick");
$person1->setGender("M");
This is just a simple but handy shortcut that I will most definitely consider when programming classes. 
That's just a little tutorial/update PHP techniques I've been getting to speed with. 

Cheers,

Nick

No comments:

Post a Comment

Feel free to leave a comment or question about my posts :)