开发者

Proper way to set up and document unlimited-parameters to function?

开发者 https://www.devze.com 2023-04-03 15:32 出处:网络
Background: I am creating a method addAll that adds all of the values passed to the method to my class.Here\'s what I was thinking:

Background: I am creating a method addAll that adds all of the values passed to the method to my class. Here's what I was thinking:

public function addAll() {
    if(func_num_args()===0) {
        throw new BadMethodCallException(get_class($this).'::addAll() must have arguments.');
    }

    $args = func_get_args();

    foreach($args as &$arg) {
        $this->add($arg);
    }
}

And it works great. Then I got to documenting it with phpDocumentor:

/**
 * @param mixed ... All of the values to add.
 */

. . . but I don't have a name for my @param because, frankly, it doesn't exist.

Question: How do I construct and define something like this?


Since I want it to have at least one value passed in, I came up with this but am unsure:

/**
 * @param mixed $value,... All of the values to add.
 */
public function addAll($value) {
    $args = func_get_args();

    foreach($args开发者_运维技巧 as &$arg) {
        $this->add($arg);
    }
}

It seems so wrong because $value is never directly used. . .

Also, I already have add which adds one, so shouldn't addAll semantically require at least two parameters? What would you recommend for defining and documenting that?


Answer: use an @example tag.

I also changed my setup, and it seems to be the best way to utilize what PHP has to offer without forfeiting usability:

/**
 * @param mixed $values Either an array of values to add, or multiple values
 * @example
 * 
 * $object->add('1');
 * $object->add('1','2');
 * $object->add(array('1','2'));
 * 
 * @return type 
 */
public function add($values=null) {
    if (is_array($values)) {
        return $this->addAll($values);
    } else {
        return $this->addAll(func_get_args());
    }
}
0

精彩评论

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

关注公众号