【问题标题】:PHP - How to get object from array when array is returned by a function?PHP - 当函数返回数组时如何从数组中获取对象?
【发布时间】:2009-06-09 17:40:35
【问题描述】:

当函数返回数组时,如何从数组中获取对象?

class Item {
    private $contents = array('id' => 1);

    public function getContents() {
        return $contents;
    }
}

$i = new Item();
$id = $i->getContents()['id']; // This is not valid?

//I know this is possible, but I was looking for a 1 line method..
$contents = $i->getContents();
$id = $contents['id'];

【问题讨论】:

标签: php arrays syntax function


【解决方案1】:

您应该使用 2 行版本。除非你有一个令人信服的理由来压缩你的代码,否则没有理由拥有这个中间值。

但是,您可以尝试类似的方法

$id = array_pop($i->getContents())

【讨论】:

  • array_pop 怎么知道它必须输出 'id' ?
  • array_pop 将返回数组中的第一个元素,无论是数字索引 $x[0] 还是关联 $['id']。有关其工作原理的更多信息,请参阅php.net/array_pop。现在,如果您的类可以对私有变量 $contents 进行进一步操作,那么这可能不可靠,但根据您在此处的内容,array_pop 将为您提供 $contents['id'] 的内容
  • 好吧,类比显示的大一点:)。我最终创建了一个返回项目的 Item($index) 函数。 $i->getContents()->Item('id');
  • array_pop 返回最后一个元素,而不是第一个。
【解决方案2】:

将其保留在两行 - 如果您必须再次访问该数组,您将拥有它。否则你会再次调用你的函数,这最终会变得更丑陋。

【讨论】:

    【解决方案3】:

    我知道这是一个老问题,但我对此的单一解决方案是:

    PHP >= 5.4

    您的解决方案应该适用于 PHP >= 5.4

    $id = $i->getContents()['id'];
    

    PHP :

    class Item
    {
        private $arrContents = array('id' => 1);
    
        public function getContents()
        {
            return $this->arrContents;
        }
    
        public function getContent($strKey)
        {
            if (false === array_key_exists($strKey, $this->arrContents)) {
                return null; // maybe throw an exception?
            }
    
            return $this->arrContents[$strKey];
        }
    }
    
    $objItem = new Item();
    $intId   = $objItem->getContent('id');
    

    只需要写一个按键获取值的方法。

    最好的问候。

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 2021-01-30
      • 2012-02-11
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多