Search code examples
php-7phpdocphp-7.2

PHPDoc return type for trait function


I have functions like the following in my code that return the object (for chaining):

    /**
     * Set properties
     *
     * @param $name
     * @param $value
     *
     * @return \Boka10\Page\MenuItemConfig
     */
    public function __set($name, $value)
    {

        $this->$name = $value;

        return $this;
    }

I want to move this function into a trait because, well, basically it is reused all the time.

My problem is, that the return $this line makes problems in the documentation section. In my PHPDoc it says (in this example) @return \Boka10\Page\MenuItemConfig.

How do I create a "global" trait method whose return documentation contains the correct typecast? Is it possible to do that or should I just add the __set function to each class?

I am not sure if I can explain what problem I am having here ;) What exactly would be the content of the @return tag in a globally used trait if all of these objects return their own instance?


Solution

  • After some digging and "hacking" I checked out the tests in Psalm and found, that the following seems to be the best method to comment these cases:

    /**
     * @method string somefunction($name, $value)
     * @property string $name
     */
    class ImplementTrait {
    
        use MagicTrait;
    
    }
    

    The properties and methods are documented on the implementing class.

    Note: I am using Psalm to check the code quality and this is psalms accepted way: