PHPStorm "Class member access on instantiation" phpDoc

266 Views Asked by At

first note: Note that this right here is not a coding problem, it is a problem I have with the IDE PhpStorm

I have a Model class in my project that has the method load which basically loads something from the database. Then I have multiple classes (other models) that extend the Model, e.g.

User extends Model
Book extends Model

Now, with the in 5.4 added feature to access class membes on instantation I have some problems with the Code Inspector from phpstorm.

In the user class I have a method "getUrl()". When I call it like that

$user = new User();
$user->load(1);
$user->getUrl();

I don't get any warnings. Phpstorm knows that $user is a User object and doesn't throw a warning.

However, when I declare it like this

$user = (new User())->load(1);
$user->getUrl();

I get the warning Method 'getUrl()' not found in class Model. I could easily fix this by adding the getUrl method to the model, but there are only 3-4 classes (of 15) which use the getUrl method. Is there a way to tell him that $user is a User object and not a Model object?

I know that I could just add

/** @var User $user */

before the code, but I want this to be automatically and not that I have to regenerate this all the time.

So basically the problem is

User class has a method called getUrl Calling that class with the class member access on instantation feature throws a warning, because PHPStorm thinks it's an object of the Model class and not of the user

1

There are 1 best solutions below

2
On

This should be solved by adding the docblock to the load() method.

The problem is, that in your second example $user is not a result of new User(), but a result of ->load() call and it looks like PHPStorm can not infer that load actually returns object of correct class

It should look like this:

<?php
class Model
{
    /**
     * @param int $id
     * @return static
     */
    public function load($id)
    {
        // …
    }
}