Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Using PHP magic methods

Thursday, August 30th, 2012 by Servage

PHP includes a brilliant concepts called overloading which means you can try to get and set undefined properties as well as run undefined methods. In this little tutorial I will show you how to handle overloadable properties. Every time an undefined property is accessed, the object will try the magic methods __set() and __get() instead of just returning an error right away. If they are defined, it works. Consider the following example class:

class Magic {

	var $data = array();

	function __construct($data) {
		foreach ($data as $key => $value)
			$this->$key = $value;
	}

	function __set($key, $value) {
		$this->data[$key] = $value;
	}

	function __get($key) {
		if (isset($this->$key))
			return $this->data[$key];
	}

	function __isset($key) {
		if (isset($this->data[$key]))
			return true;
		else
			return false;
	}

	function __unset($key) {
		if (isset($this->$key))
			unset($this->data[$key]);
	}

}

You can use this class to extend other classes with this basic property overloading, to store properties inside the data variable:

class Person extends Magic {

  function getName() {
    return $this->first_name.' '.$this->last_name;
  }

}

Now you can do all of the following nice stuff:

$data = array(
	'first_name' => 'John',
	'last_name' => 'Doe',
);
$person = new Person($data);
echo $person->getName();

$person->first_name = 'John';
$person->last_name = 'Doe';

isset($person->first_name)
unset($person->first_name)

Check out more in the PHP manual.

Using PHP magic methods, 4.0 out of 5 based on 4 ratings
Categories: Guides & Tutorials, Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.