Sharing Our Passion for Technology
& continuous learning
〈  Back to Blog

Add some "magic" to PHP apps: Dynamic properties

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
〈  Back to Blog