PhpStorm, return value is expected to be 'A', 'object' returned

✔ Recommended Answer

Has to be because object can be ANY class instance, even B etc.

You can annotate the create() method with generics PHPDoc to tell that the return type will be the same as the input parameter class string. It gives more context info to the IDE.

    /**     * @template T     *     * @param string $class     * @return T     */    private function create(string $class) : object    {        return new $class();    }

enter image description here


Instead of create('B'); better use create(B::class). This way the IDE can track the usages of that class for refactoring/search purposes etc.


Answered By: LazyOne

Method #2

This error message suggests that your code is expecting a value of type 'A' to be returned, but instead, the code is returning an object. This error can occur in PhpStorm, or any other PHP development environment.

To resolve this error, you should check the function or method that is returning the object and ensure that it is returning a value of the expected type. You may need to modify the function or method to return the correct type, or update the code that is calling the function to handle the returned object correctly.

It's also possible that the error is caused by a type hint or return type declaration in the function or method signature. In this case, you may need to update the type hint or return type declaration to match the actual type of the value being returned.

Once you have made the necessary changes, you should re-run your code to ensure that the error has been resolved. If the error persists, you may need to review your code further to identify any other issues that may be causing the error.


Most Popular

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755