Saturday, March 24, 2007

Member overloading

Overloading

Both method calls and member accesses can be overloaded via the __call, __get and __set methods. These methods will only be triggered when your object or inherited object doesn't contain the member or method you're trying to access. All overloading methods must not be defined as static. In PHP 5.0.x, all overloading methods must be defined as public.

Since PHP 5.1.0 it is also possible to overload the isset() and unset() functions via the __isset and __unset methods respectively.
Member overloading
void __set ( string name, mixed value )
mixed __get ( string name )
bool __isset ( string name )
void __unset ( string name )
Class members can be overloaded to run custom code defined in your class by defining these specially named methods. The $name parameter used is the name of the variable that should be set or retrieved. The __set() method's $value parameter specifies the value that the object should set the $name.


<?php
class Setter
{
public $n = 1;
private $array_x = array('x' => 1, 'y' => 2, 'z' => 3);

private function __get($var)
{
echo "Getting {$var}: <br />";
if(isset($this->array_x[$var]))
{
return $this->array_x[$var] . "<br/>";
}
else
{
echo "Nothing get {$var} in array_x. <br />";
}
}

private function __set($name, $value)
{
echo "Setting {$value} to {$name}. <br/>";
if(isset($this->array_x[$name]))
{
$this->array_x[$name] = $value;
}
else
{
echo "{$name} Nothing find in array_x.<br/>";
}
}

private function __isset($name)
{
echo "isset {$name} ? ";
if(isset($this->array_x[$name]))
{
echo "Yes.<br/>";
}
else
{
echo "No.<br/>";
}
}

private function __unset($name)
{
echo "unset {$name} <br/>";
unset($this->array_x[$name]);
}
}
$s = new Setter();
echo $s->x;
echo $s->y;
$s->y = 100;
echo $s->y;
isset($s->x);
isset($s->a);
// echo isset($s->n);
$s->z;
unset($s->z);
isset($s->z);
?>

No comments :