Magic methods
There are several magic methods in PHP which save you time by limiting what code has to be written to access methods, getters and setters etc.
__get($val) allows you to have a get method on a class without actually creating a get method so.
When a get or set is called on a class, PHP looks to see if there is a explicitly defined property which is visible before calling a magic __get or __set method.
class Example
{
private $counter;
private $name;
private $age;
function __get($var)
{
if (!empty($var))
{
return $this->$var;
}
}
}
This will mean that the below code will get the private variables without any getters needing to be written in the class.
$example = new Example();
$example->name;
$example->counter;
Unfortunatley it also allowed us to access counter which, should be kept internal to the class. A better way therefore of doing this is.
class Example
{
private $counter;
private $vars;
function __get($var)
{
if (!empty($var) && !empty($vars[$var]))
{
return $this->$vars[$var];
}
}
}
This will then ensure that values are only read from the private array and no other private variables are exposed.
__set() is quite similar to __get except that it is a setter rather than a getter.
This will set a value in the following way.
class Example
{
private $name;
function __set($var, $value)
{
if (!empty($var))
{
$this->$var = $value;
}
}
}
This can be used in the following way:
$example = new Example();
$example->name = 'Dominic';
Again a private array could be used to protect the protection of the other variables in the class.
No comments have been provided.
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38