Reputation: 28124
Although this question is about DocBlocks in general, my use-case is about PHP.
Consider the following PHP code:
<?php
class ParentClass {
/**
* Says 'hi' to the world.
* @return ParentClass Returns itself for chaining.
*/
public function say_hi(){
echo 'hi';
return $this;
}
}
class ChildClass extends ParentClass {
/**
* Says 'bye' to the world.
* @return ChildClass Returns itself for chaining.
*/
public function say_bye(){
echo 'bye';
return $this;
}
}
$c = new ChildClass;
$c->say_hi()->say_b| <- type hinting won't suggest "say_bye" here
?>
This is just a trivial class with some chaining. The extended class looses type hinting because the parent class' docblock is making use of a specific class name which does not have the methods/properties of the child class.
Assuming we do want type-hinting capability, (if not, please leave this question - I don't want useless arguments here), how should I fix this?
I came up with the following possibilities:
return $this;
means (does this even work?)Upvotes: 5
Views: 2540
Reputation: 75
You can solve this like this :
class ParentClass {
/**
* Says 'hi' to the world.
* @return static
*/
public function say_hi(){
echo 'hi';
return $this;
}
}
The "@return static" statement allows exactly what you want, PhpStorm works just fine with it.
Upvotes: 6
Reputation: 6688
What you describe is commonly called a "fluent interface", where all of an object's methods do their work and return the object itself.
I have not personally seen any PHPDoc guideline finalized on how to do exactly that. As such, I'm not aware that any IDE has put forth a means for its autocomplete functionality to handle the use case.
A likely path that PHPDoc will take on this is to utilize "@return $this" to be the convention to indicate fluent methods, as it matches the code syntax itself and is therefore very clear. I doubt that any IDEs will build that capability in until the standard itself incorporates this use case.
In the short term, I think that your superfluous "ChildClass::say_hi(){parent::say_hit();}" might get your IDE autocompletion to work. Again, might, because having the autocomplete also recognize method chaining itself (e.g. $foo->bar()->baz()->roll()->tide();) might not exist.
Upvotes: 2