-1

如果我有以下类示例:

<?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:是否可以从函数返回多个值?

祝你好运!

4

2 回答 2

2

你听起来像是想要__get()魔法的方法

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();
于 2012-11-14T15:56:12.680 回答
1

也许

public function getAll() {
    return(array('prefix' => $this->prefix, 'givenName' => $this->giveName, etc...));
}
于 2012-11-14T15:48:26.670 回答