Assigning a function leads to a variable inside a PHP class? Tumor

I know that you can assign a return value function to a variable and use it, for example:

function standardModel()
{
    return "Higgs Boson";   
}

$nextBigThing = standardModel();

echo $nextBigThing;

So will someone tell me why the following does not work? Or is it not yet implemented? Did I miss something?

class standardModel
{
    private function nextBigThing()
    {
        return "Higgs Boson";   
    }

    public $nextBigThing = $this->nextBigThing();   
}

$standardModel = new standardModel;

echo $standardModel->nextBigThing; // get var, not the function directly

I know that I could do this:

class standardModel
{
    // Public instead of private
    public function nextBigThing()
    {
        return "Higgs Boson";   
    }
}

$standardModel = new standardModel;

echo $standardModel->nextBigThing(); // Call to the function itself

But in my project case, all the information stored in the class is predefined public vars, except one of them, which should calculate the value at runtime.

I want it to be consistent so that I or some other developer using this project does not remember that one value should be a function call, not a var call.

, , PHP-?

, . , "" . , . !

+3
3
public $nextBigThing = $this->nextBigThing();   

. - . , , , , , , , .

:

class standardModel {

    public $nextBigThing = null;

    public function __construct() {
        $this->nextBigThing = $this->nextBigThing();
    }

    private function nextBigThing() {
        return "Higgs Boson";   
    }

}
+7

, (, , int... ..). , (, , $_SESSION), . , .

class test {
    private $test_priv_prop;

    public function __construct(){
        $this->test_priv_prop = $this->test_method();
    }

    public function test_method(){
        return "some value";
    }
}
+6
class standardModel
{
// Public instead of private
public function nextBigThing()
{
    return "Higgs Boson";   
}
}

$standardModel = new standardModel(); // corection

echo $standardModel->nextBigThing(); 
-2
source

Source: https://habr.com/ru/post/1761433/


All Articles