Should I use @return self, this or the current class?

PhpDocumentationPhpdocDoc

Php Problem Overview


I have a method that return the current object, how do I document this?

/**
 * set something
 *
 * @return this
 */
public function setSomething(){
            // ...
	return $this;
}

Or should I do @return self or @return Current_Class_Name?


Reason why this question is not "primarily opinion-based" (and should be reopened): conformance to standards and IDE type hinting support.

Php Solutions


Solution 1 - Php

There is a PHP Standards Recommendation (PSR) currently in draft (PSR-5) that proposes @return $this is used in order to indicate that the same instance is returned.

> $this, the element to which this type applies is the same exact instance as the current class in the given context. As such this type is a stricter version of static as, in addition, the returned instance must not only be of the same class but also the same instance. > >This type is often used as return value for methods implementing the Fluent Interface design pattern.

This notation is currently used by popular IDEs such as PhpStorm and Netbeans.

Solution 2 - Php

@return Current_Class_Name will definitely work and is what I prefer.

@return self may work ok with some programs too.

@return this is bad because this is not a typename.

Solution 3 - Php

This question is quite old, but I just want to share to everyone!

AT LEAST for the ones that uses NetBeans 8.1.. this notation makes code autocompletion to nicely work at IDE:

/**
 * Method that returns $this instance (using late state binding)
 * @return static
 */
 public function iWillReturnMyself ( ) {
 	 return $this;
 }

I say AT LEAST for NetBeans8.1 users, but may work on older versions and/or others IDEs too =]

Solution 4 - Php

/**
 * set something
 *
 * @return self
 */
public function setSomething(){
            // ...
    return $this;
}

You can use "self" type as @param or @return..

PHPDoc recommends 'self' to refer to self in object..

Source: http://www.phpdoc.org/docs/latest/references/phpdoc/types.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlucaswxpView Question on Stackoverflow
Solution 1 - Phpg .View Answer on Stackoverflow
Solution 2 - PhpRiaDView Answer on Stackoverflow
Solution 3 - PhpDiego CaleroView Answer on Stackoverflow
Solution 4 - PhpMURATSPLATView Answer on Stackoverflow