0

给定一个函数,该函数的行为取决于传递给它的参数,它既可以是 mutator 也可以是 accessor,如下所示:

// in PHP, you can pass any number of arguments to a function...
function cache($cacheName) {
    $arguments = func_get_args();

    if (count($arguments) >= 2) {   // two arguments passed. MUTATOR.

        $value = $arguments[1];             // use the second as the value
        $this->cache[$cacheName] = $value;  // *change* the stored value

    } else {    // 1 argument passed, ACCESSOR
        return $this->cache[$cacheName];  // *get* the stored value
    }
}

cache('foo', 'bar');  // nothing returned
cache('foo')          // 'bar' returned

您如何在 PHPDoc 或类似的自动文档创建器中记录这些内容?我最初只是这样写的:

/**
 *  Blah blah blah, you can use this as both a mutator and an accessor:
 *    As an accessor:
 *    @param   $cacheName   name of the variable to GET
 *    @return  string       the value...
 *
 *    As a mutator:
 *    @param   $cacheName   name of the variable to SET
 *    @param   $value       the value to set
 *    @return  void
 */

但是,当它通过 phpDoc 运行时,它会报错,因为有 2 个返回标签,并且第一个@param $cacheName描述被第二个覆盖。

有没有解决的办法?

4

1 回答 1

2

正如您所发现的,您不能记录单个函数的 2 个不同签名。但是,如果您使用phpDocumentor,您可以做的是记录可选的函数参数多种可能的返回类型

/**
 * Blah blah blah, you can use this as both an accessor and a mutator, e.g.
 * <code>cache('name') // get cache value</code>
 *   and
 * <code>cache('name', 'value') // set new cache value</code>.
 *
 * @param   string  $cacheName  name of the variable to GET|SET
 * @param   string  $value      optional new value
 *
 * @return  string|void value of $cacheName or, in case of mutator, void
 */

为清楚起见,我还将包括使用示例。

于 2010-05-20T07:42:29.003 回答