Sobrecarga

Las llamadas a métodos y los accesos a los miembros pueden ser sobrecargadas por medio de los métodos __call, __get y __set. Estos métodos serán accionados cuando su objeto u objeto heredado no contengan los miembros o métodos que está intentado accesar. All overloading methods must not be defined as static

Since PHP 5.1.0 it is also possible to overload the isset() and unset() functions via the __isset and __unset methods respectively.

Sobrecarga de Miembros

void __set ( string name, mixed value )

mixed __get ( string name )

bool __isset ( string name )

void __unset ( string name )

Los miembros de la clase pueden ser sobrecargados para ejecutar código personalizado definido en la clase al definir estos métodos de nombre especial. El parámetro $name usado es el nombre de la variable que debe ser asignada (set) u obtenida (get). El parámetro $value del método __set() especifica el valor que el objeto debe tener $value.

Ejemplo 19-18. Ejemplo de sobrecarga con with __get, __set, __isset y __unset
<?phpclass Setter{
    
public $n;
    
private $x = array("a" => 1"b" => 2"c" => 3);

    
private function __get($nm)
    {
        echo 
"Getting [$nm]\n";

        if (isset(
$this->x[$nm])) {
            
$r $this->x[$nm];
            print 
"Returning: $r\n";
            return 
$r;
        } else {
            echo 
"Nothing!\n";
        }
    }

    
private function __set($nm$val)
    {
        echo 
"Setting [$nm] to $val\n";

        if (isset(
$this->x[$nm])) {
            
$this->x[$nm] = $val;
            echo 
"OK!\n";
        } else {
            echo 
"Not OK!\n";
        }
    }

    
private function __isset($nm)
    {
        echo 
"Checking if $nm is set\n";

        return isset(
$this->x[$nm]);
    }

    
private function __unset($nm)
    {
        echo 
"Unsetting $nm\n";

        unset(
$this->x[$nm]);
    }
}
$foo = new Setter();$foo->1;$foo->100;$foo->a++;$foo->z++;
var_dump(isset($foo->a)); //trueunset($foo->a);var_dump(isset($foo->a)); //false

// this doesn't pass through the __isset() method
// because 'n' is a public property
var_dump(isset($foo->n));
var_dump($foo);?>

El resultado del ejemplo seria:
Setting [a] to 100
OK!
Getting [a]
Returning: 100
Setting [a] to 101
OK!
Getting [z]
Nothing!
Setting [z] to 1
Not OK!

Checking if a is set
bool(true)
Unsetting a
Checking if a is set
bool(false)
bool(true)

object(Setter)#1 (2) {
    ["n"]=>
    int(1)
    ["x:private"]=>
    array(2) {
        ["b"]=>
        int(2)
        ["c"]=>
        int(3)
    }
}

No response to “Sobrecarga”