Eseguire un metodo quando una variabile di istanza viene fatto riferimento in una classe PHP?

StackOverflow https://stackoverflow.com/questions/4670991

Domanda

E 'possibile eseguire una funzione quando si parla di una variabile in una classe PHP piuttosto che semplicemente restituire il suo valore, simile alla capacità di javascript per una variabile per contenere un metodo?

class LazyClassTest()
{

    protected $_lazyInitializedVar;

    public function __construct()
    {
        /* // How can this call and return runWhenReferrenced() when
           // someone refers to it outside of the class:
           $class = new LazyClass();
           $class->lazy;
           // Such that $class->lazy calls $this->runWhenReferrenced each
           // time it is referred to via $class->lazy?
         */
        $this->lazy = $this->runWhenReferrenced();
    }

    protected function runWhenReferrenced()
    {
        if (!$this->_lazyInitializedVar) {
            $this->_lazyInitializedVar = 'someValue';
        }

        return $this->_lazyInitializedVar
    }

}
È stato utile?

Soluzione

Questo suona come PHP5.3: lambda / chiusure / funzioni anonime

http://php.net/manual/en/functions.anonymous.php :

<?php
$greet = function($name) {
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

Altri suggerimenti

PHP5s magia metodo __get($key) e __set($key, $value) potrebbe essere quello che ti serve. Maggiori informazioni su di loro è disponibile nel manuale PHP .

Probabilmente si sta andando nella direzione sbagliata. Normalmente si vuole definire un getLazyVar() getter. C'è un motivo per cui le persone fanno sempre le proprietà protette e getter / setter definiti:. Così possono pre- o post elaborazione dei valori

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top