Accedere a tutte le proprietà di un oggetto

  • Creatore Discussione Creatore Discussione Eliox
  • Data di inizio Data di inizio

Eliox

Utente Attivo
25 Feb 2005
4.390
3
0
Lo sapevi che con PHP 5.4 puoi accedere praticamente a tutte le proprietà di un oggetto? No? Prova (ma prima ripassati le closures):
PHP:
class Icchisi {
    private $mambanero = "x";
 
    function drinGhede($intercetta) {
        return function() use ($intercetta) {
            return $this->$intercetta;
        };
    }
 
    function dranGhede() {
        return function($intercetta)  {
            return $this->$intercetta;
        };
    }
}
 
$obj = new Icchisi();
$daje = $obj->drinGhede('mambanero');
echo $daje();
$aridaje = $obj->dranGhede();
echo $aridaje('mambanero');
Avete notato che il livello di visibilità di $mambanero è private?
 
Ultima modifica:
L'accento qui va messo sul fatto che in PHP 5.4 le closure possono accedere allo scope della classe in cui vengono definite usando $this (che prima restituiva l'errore "using $this when not in object context").

P.S. Io avrei fatto così anche in PHP 5.4, comunque. :D
PHP:
<?php
class MyClass
{
    private $var = 'foo';
    protected $var2 = 'bar';
    public $var3 = 'baz';

    public function __get($property)
    {
        if (!isset($this->$property)) {
            throw new \ErrorException(sprintf(
                'Undefined property "%s::%s".',
                get_class($this),
                $property
            ));
        }

        return $this->$property;
    }
}

$class = new MyClass();
var_dump($class->var, $class->var2, $class->var3);
?>
 

Discussioni simili