开发者

Dynamic return type with type hint in PHP?

For a standard method, I know one can specify return type in the comments such as:

/**
 * Load this entity from the database with the specified primary key.
 * @param int $Key
 * @return BaseEntity
 */
public static function Load($Key)
{ ... }

I would like to have the return type change depending on the subclass. Something like:

 * @return __CLASS__

In other languages, this could be accomplished using templates etc. Do I have any op开发者_如何学运维tions for PHP?


No. Not unless you code something to generate this code.

Those are comments, they will not change the way that the code runs. They may be used by your IDE for code hints, or by PHPDoc to generate documentation. Those applications may have ways of doing something like what you want, check their documentation. The comments will not, however, affect the way your code runs.


You want to extend your BaseEntity with, say, SubclassEntity and tighten up the interface, so to speak. But, tightening your interface is breaking your interface.

Conceptually, Load should always return a BaseEntity, even if you happen to know it's really a SubclassEntity. In reality, if you know the returned object is a SubclassEntity, then just add this after:

$obj = $container->Load(123); /* @var $obj SubclassEntity */
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜