PHP, calling static method on class property

前端 未结 2 1533
醉话见心
醉话见心 2021-01-22 12:44

I have a desire to store an object as a property of a class. I then want to be able to call static methods on that class by directly referencing the property.

Consider t

相关标签:
2条回答
  • 2021-01-22 12:55

    The error that syntax will give you is:

    Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)


    However it will work in PHP 7 thanks to the Uniform Variable Syntax RFC. All prior versions will require the intermediate variable.

    0 讨论(0)
  • 2021-01-22 13:07

    The reason it fails on $results = $this->models->myModel::all(); is because the public property $models from myClass does not have a property myModel (since it's NULL from start), which you try to access by ->myModel. As you stored an instance of myModel inside $models non existing instance myModel, it's probably not properly created. You need to fix this $this->models->myModel = new myModel; to $this->models = new myModel; as well, since $models is not an object with a property myModel but you tried to access ist. Then, $this->models directly points to the object myModel and you can access the static method by $this->models::all().

    0 讨论(0)
提交回复
热议问题