【问题标题】:PHP 5 how to call multiple values from one function?PHP 5 如何从一个函数调用多个值?
【发布时间】:2012-11-14 15:46:23
【问题描述】:

如果我有以下类示例:

<?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?

祝你好运!

【问题讨论】:

  • 你为什么不直接返回一个数组??或者你到底在期待什么?
  • 我是 PHP 的 OOP 新手,但看起来代码可以被压缩,在知道返回什么和不返回什么的意义上,为什么向下滚动一百万行代码到当您可以从单个构造函数控制所有返回的函数时,查看返回的是什么函数。
  • 当然可以!自己返回对象即可:return $this;
  • 好的,这对我来说很有意义。当归结为在类中返回选择性 PHP 函数时,我只需要学习如何正确返回它
  • 您可能会为此使用魔法__set and __get

标签: php oop class design-patterns


【解决方案1】:

听起来你想要__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();

【讨论】:

  • 或者只是将私有重命名为公共并删除所有那些无用的方法
  • OR 保持现状并考虑您希望允许公共 读取 访问但限制写入访问的情况。此外,因为您可以编写自己的访问器,您可以大大扩展 $obj->prop 在后台的实际作用。
  • 感谢 Sammitch 的帮助!这看起来很有趣。
【解决方案2】:

也许

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

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多