2

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 the following:

class myModel {
    public static function all()
    {
        return 1;
    }
}

class myClass {
    public $models;

    public function __construct()
    {
        $this->models->myModel = new myModel;
        $results = $this->models->myModel::all();
    }
}

$result = new myClass;

PHP fails on $results = $this->models->myModel::all();

If I modify this by assigning the class property to a local variable, things work as expected:

$myModel = $this->models->myModel;
$results = $myModel::all();

I'd like to eliminate the need to assign the class property to a local variable.

Is this possible in PHP 5.3.x (the version I'm using) or indeed, in later versions?

The solution should be readable and the purpose of the code should not be otherwise obfuscated.

For clarity, this is a dramatic simplification of the working code. The benefits of storing the object in a class property are not evident in the example code I have posted.

1
  • You are getting Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) ?? Commented Oct 18, 2015 at 13:36

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I suspected this was an arrangement that PHP does not currently support. Thank you for the clarification and pointer to relevant docs.
0

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().

1 Comment

The class property exists as advertised. I can assign it to a local variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.