Assigning a function's result to a variable wi

2019-01-26 19:55发布

问题:

I know you can assign a function's return value to a variable and use it, like this:

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

$nextBigThing = standardModel();

echo $nextBigThing;

So someone please tell me why the following doesn't work? Or is it just not implemented yet? Am I missing 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 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's case, all of the information stored in the class are predefined public vars, except one of them, which needs to compute the value at runtime.

I want it consistent so I nor any other developer using this project has to remember that one value has to be function call rather then a var call.

But don't worry about my project, I'm mainly just wondering why the inconsistency within PHP's interpreter?

Obviously, the examples are made up to simplify things. Please don't question "why" I need to put said function in the class. I don't need a lesson on proper OOP and this is just a proof of concept. Thanks!

回答1:

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

You can only initialize class members with constant values. I.e. you can't use functions or any sort of expression at this point. Furthermore, the class isn't even fully loaded at this point, so even if it was allowed you probably couldn't call its own functions on itself while it's still being constructed.

Do this:

class standardModel {

    public $nextBigThing = null;

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

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

}


回答2:

You can't assign default values to properties like that unless that value is of a constant data type (such as string, int...etc). Anything that essentially processes code (such as a function, even $_SESSION values) can't be assigned as a default value to a property. What you can do though is assign the property whatever value you want inside of a constructor.

class test {
    private $test_priv_prop;

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

    public function test_method(){
        return "some value";
    }
}


回答3:

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

$standardModel = new standardModel(); // corection

echo $standardModel->nextBigThing();