Question

Is it possible to run a function when referring to a variable in a php class rather than simply returning its value, similar to javascript's ability for a variable to hold a method?

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
    }

}
Was it helpful?

Solution

This sounds like PHP5.3: lambda / closures / anonymous functions

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

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

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

OTHER TIPS

PHP5s magic method __get($key) and __set($key, $value) might be what you need. More information about them is available in the PHP manual.

You are probably heading in the wrong direction. You normally want to define a getter getLazyVar(). There is a reason why people always make properties protected and defined getters / setters: So they can pre- or postprocess the values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top