1

PHP 中的函数或方法是否可以确定调用者是否需要数组返回值(ala Perl 的wantarray运算符)?具体来说,我想创建一个__get()魔术方法,如果调用者需要一个数组,它会自动返回一个数组,如果不是,则返回一个合理的标量值。所以是这样的:

public function __get($name)
{
    if (wantarray())
    {
        // data is stored internally as an array of arrays
        // return appropriate array as-is
        return $this->data[$name];  
    }
    else
    {
        // caller doesn't expect an array, return imploded string instead
        return implode(', ', $this->data[$name]);
    }
}

基本上,PHP 是否有等效于 Perl 的wantarray运算符或以其他方式允许确定这种调用上下文?

4

1 回答 1

1

不,你不能用 PHP 做到这一点。

您只需要返回$this->data[$name]并让调用者决定是否需要这样做implode

于 2012-07-30T09:11:22.820 回答