0

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
    }

}

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hmmm... not all of us understand German, so why not share the English manual? :-)
While this is not what I was looking for, I actually ended up using it and it helped, so thanks!
1

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');
?>

Comments

1

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.

1 Comment

I agree that it's good practice to use the getLazyVar() practice but my reason for wanting a variable is to keep the class's pattern consistent with other similarly patterned classes that I have so that a method's properties will always be accessible in the exact same way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.