Add some “magic” to PHP apps: Dynamic properties

November 1st, 2009 by Octavian Covalschi Leave a reply »

There are no doubts that PHP made a huge impact on Web development industry. Because of it’s flexibility, PHP finds it’s usage in many areas, starting from simple Web sites and ending with complex Web applications (i.e. frameworks, shopping carts, etc…).

So, today I’d like to share with you how can a simple feature bring back/more fun to daily development. Let’s talk about “magic methods”.

“Magic methods” are class methods that start with double-underscores “__”. PHP has more than 1 of them, however today we’ll make usage only 4 of them: __set, __get, __isset, __unset.

So, what’s so special about them? You could use them to make your object more adaptive, you could have dynamic and unlimited properties.
For example we have a simple User class:

class User {
private $name;
}

At the time of it’s writing I don’t know how many properties it will have, and later when I’ll need new properties, I’ll have to add them, right?. However there is another option, to have a super class that will handle calls to unknown/non-existing properties. The idea would be to store all data in an associative array (a map if you want) and place this functionality into a super class that we’ll extend.

class AbstractModel {
  private $data = array();
 
protected function __set($name, $value) {
  $this->data[$name] = $value;
}
 
protected function __get($name) {
  if (array_key_exists($name, $this->data)) {
     return $this->data[$name];
  }
  return null;
}
 
protected function __isset($name) {
  return isset($this->data[$name]);
}
 
protected function __unset($name) {
  unset($this->data[$name]);
 }
}

__set method will be called when we’ll try to assign a value to a non-existing property.

$obj->nonExistingProperty = "Some value";

will trigger

__set("nonExistingProperty", "Some value");

__get method will be called when we’ll want to retrieve value of our property.

echo $obj->nonExistingProperty;

will trigger

__get("nonExistingProperty");

Similar to __set and __get, __isset and __unset will be triggered when we’ll use isset and unset functions on non-existing properties.

Usage of our “magic”.

class User extends AbstractModel {
}
include "User.php";
define ('NL', '<br>');
 
$u = new User();
 
$u-&gt;name = "John Rambo";
$u-&gt;age = 87;
 
echo $u-&gt;name . NL;
echo $u-&gt;age . NL;
 
if (isset($u-&gt;name)) {
  echo "Name is set" . NL;
}
 
if (isset($u-&gt;age)) {
  echo "Age is set" . NL;
}
 
if (!isset($u-&gt;email)) {
  echo "Email is NOT set" . NL;
}

Output:

John Rambo
87
Name is set
Age is set
Email is NOT set

Advertisement

1 comment

  1. tifacil says:

    Good morning, thanks for the interesting article? Is your blog a free theme or paid? I am intrigued by your blog. Is it possible to include this post on one of my sites?, i will of course linkback to this page. regards

Leave a Reply