PHP 5如何从一个函数调用多个值?

时间:2012-11-14 15:46:23

标签: php oop class design-patterns

如果我有以下课程示例:

<?php
class Person
{
    private $prefix;
    private $givenName;
    private $familyName;
    private $suffix;

    public function setPrefix($prefix)
    {
        $this->prefix = $prefix;
    }

    public function getPrefix()
    {
        return $this->prefix;
    }

    public function setGivenName($gn)
    {
        $this->givenName = $gn;
    }

    public function getGivenName()
    {
        return $this->givenName;
    }

    public function setFamilyName($fn)
    {
        $this->familyName = $fn;
    }

    public function getFamilyName() 
    {
        return $this->familyName;
    }

    public function setSuffix($suffix)
    {
        $this->suffix = $suffix;
    }

    public function getSuffix()
    {
        return $suffix;
    }

}

$person = new Person();
$person->setPrefix("Mr.");
$person->setGivenName("John");

echo($person->getPrefix());
echo($person->getGivenName());

?>

我在PHP中有一种方法(最好是5.4),将这些返回值组合成一个函数,这样它的模型更像是在JavaScript中显示模块模式吗?

更新 好的,我现在开始学习在PHP中,从函数返回单个值是规范的,但是你“可以”返回多个值的数组。这是我的问题的最终答案,以及我将通过这种理解深入研究一些实践。

小例子 -

function fruit () {
return [
 'a' => 'apple', 
 'b' => 'banana'
];
}
echo fruit()['b'];

还有一篇关于主题的stackoverflow上的文章... PHP: Is it possible to return multiple values from a function?

祝你好运!

2 个答案:

答案 0 :(得分:2)

你听起来像是想要__get() magic method

class Thing {

private $property;

public function __get($name) {
    if( isset( $this->$name ) {
        return $this->$name;
    } else {
        throw new Exception('Cannot __get() class property: ' . $name);
    }
}

} // -- end class Thing --

$athing = new Thing();
$prop = $athing->property;

如果你想要一次返回所有值,就像在Marc B的例子中那样,我会简化它的类设计:

class Thing {

private $properties = array();

public function getAll() {
    return $properties;
}

public function __get($name) {
    if( isset( $this->properties[$name] ) {
        return $this->properties[$name];
    } else {
        throw new Exception('Cannot __get() class property: ' . $name);
    }
}

} // -- end class Thing --

$athing = new Thing();
$prop   = $athing->property;
$props  = $athing-> getAll();

答案 1 :(得分:1)

也许

public function getAll() {
    return(array('prefix' => $this->prefix, 'givenName' => $this->giveName, etc...));
}