简体   繁体   中英

Reference or call a function through variable in a php class

why can't i assign a function to a variable within a class: eg

class call {
    public $number = function() {
        return 3 * 2;
    }
}
$num = new call();
$num->number // expecting output 6

Is it possible to assign a method (function) to a property (variable) so that the method can be called outside the class just as a property. eg

class call {
    public $number = $this->value();
    private function value() {
        return 3 * 2;
    }
}

$num = new call();
echo $num->$number // expecting output 6;

Use __get() magic method that called when you trying to get value of inaccessible properties

class call {
    public function __get($name) {
        if ($name == 'number')
            return $this->value();
    }
    private function value() {
        return 3 * 2;
    }
}

$num = new call();
echo $num->number;
// 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM