Page MenuHomePhabricator

Is "@return $this" a valid return type declaration?
Closed, DeclinedPublic

Event Timeline

@return self or @return static means it will return something that is of the same type.

  • For example Foo::newFromX could use return self. Or, if it supports subclassing and honours LSB , then return static instead.
  • Another example could be a instance method that creates a derivative object. The class ImmutableDate could have a method addDay() that returns a new instance that is like the original with one day later.

@return $this is different. It means there is a fluent or chainable interface that returns the same exact same object instance (same identitiy).

  • This is what rdbms/SelectQueryBuilder, mw/HTMLForm, and PHPUnit/MockBuilder use.

I agree with Krinkle.

@return $this is rare. Personally I don't use it, but prefer @return self instead – which is correct as well. However, I don't think there is anything wrong with @return $this and would not touch it.

But mw/HTMLForm does not use this style.

	 * @return HTMLForm $this for chaining calls (since 1.20)
	public function prepareForm() {
	+38 more cases

	 * @return $this
	public function setFormIdentifier( $ident ) {

I don't think it needs to. @return self is certainly correct. Code that does return $this; at the end just does not return some instance of itself, but the same instance. That's why some people prefer @return $this. But I, personally, would argue this is personal preference and does not need to be enforced by a sniff, neither way.