开发者

In phpDoc, how do I write a class I don't know yet will be returned?

开发者 https://www.devze.com 2023-02-06 06:25 出处:网络
The following is code for Base.php 开发者_JS百科and the class Base /** * @return ? */ public static function withId($id, $class = __CLASS__)

The following is code for Base.php 开发者_JS百科and the class Base

/**
 * @return ?
 */
public static function withId($id, $class = __CLASS__)
{
    $instance = new $class($id);
    if ($instance->getId() == self::ID_OF_UNKNOWN_USER) {
        $instance = null;
    }
    return $instance;
}

Other classes will extend this class. I'm using late static binding to figure out who should be created prior to calling withId() and passing the class name as $class.

The returned class could be Base or any of its children. How do I mark that in phpDoc?


This looks somewhat like a factory pattern, in which case the user code shouldn't know the concrete class returned. Usually you'd use an abstract class or interface and program for that. In this case:

/**
 * @return null|Base
 */

There's no way to use values generated at runtime in docstrings (which are static).


The returned class could be Base or any of its children. How do I mark that in phpDoc?

Straight forward.

/**
 * @return Base
 */
0

精彩评论

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