Assigning a function's result to a variable within a PHP class? OOP Weirdness

前端 未结 3 1202
悲哀的现实
悲哀的现实 2020-12-06 20:43

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

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

$nextBigTh         


        
相关标签:
3条回答
  • 2020-12-06 20:46

    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";
        }
    }
    
    0 讨论(0)
  • 2020-12-06 20:48
    class standardModel
    {
    // Public instead of private
    public function nextBigThing()
    {
        return "Higgs Boson";   
    }
    }
    
    $standardModel = new standardModel(); // corection
    
    echo $standardModel->nextBigThing(); 
    
    0 讨论(0)
  • 2020-12-06 20:59
    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";   
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题