php - php中对象/关联数组的解构赋值

标签 php destructuring

在 CoffeeScript、Clojure、ES6 和许多其他语言中,我们对对象/ map /等的解构有点像这样:

obj = {keyA: 'Hello from A', keyB: 'Hello from B'}
{keyA, keyB} = obj

我找到了 list function在 php 中,它可以让你像这样解构数组:

$info = array('coffee', 'brown', 'caffeine');
list($drink, $color, $power) = $info;

有没有办法在 PHP 中解构对象或关联数组?如果不在核心库中,也许有人写了一些智能辅助函数?

最佳答案

对于 PHP 7.0 及更低版本,这超出了 list 的功能。文档状态:

list only works on numerical arrays and assumes the numerical indices start at 0.

可能适合您目的的事情之一是 extract()将数组中的变量导入当前符号表的函数。虽然使用 list 您可以显式定义变量名称,但 extract() 没有给您这种自由。

提取关联数组

使用 extract 你可以做这样的事情:

<?php

$info = [ 'drink' => 'coffee', 'color' => 'brown', 'power' => 'caffeine' ];
extract($info);

var_dump($drink); // string(6) "coffee"
var_dump($color); // string(5) "brown"
var_dump($power); // string(8) "caffeine"

提取对象

提取对象的工作方式几乎相同。由于 extract 仅将数组作为参数,因此我们需要将对象属性作为数组获取。 get_object_vars为你做那件事。它返回一个关联数组,其中所有 public 属性作为键,它们的值作为值。

<?php

class User {

    public $name = 'Thomas';

}

$user = new User();
extract( get_object_vars($user) );

var_dump($name); // string(6) "Thomas"

陷阱

extract()list 不同,因为它不允许您显式定义导出到符号表的变量名。变量名默认对应数组键。

  • list 是一个语言结构,而 extract() 是一个函数
  • 您可能会无意中覆盖预先定义的变量
  • 您的数组键作为变量名可能无效

使用可以作为第二个参数传递给 extract()$flags 参数,您可以在发生冲突或无效变量时影响行为。但了解 extract() 的工作原理并谨慎使用它仍然很重要。

编辑:从 PHP 7.1 开始,这是可能的:

http://php.net/manual/en/migration71.new-features.php#migration71.new-features.support-for-keys-in-list

You can now specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys.

https://php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring

The shorthand array syntax ([]) may now be used to destructure arrays for assignments (including within foreach), as an alternative to the existing list() syntax, which is still supported.

例如这个:

$test_arr = ['a' => 1, 'b' => 2];
list('a' => $a, 'b' => $b) = $test_arr;
var_dump($a);
var_dump($b);

从 7.1.0 开始将输出以下内容

int(1) 
int(2)

关于php - php中对象/关联数组的解构赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28232945/

相关文章:

php - 使用 Laravel 4 队列将邮件发送到多个地址

javascript - 基于特定表行的 SQL 字符串中使用的表数据

javascript - 解构多级并将默认值分配给第一级对象

Python赋值解构

javascript - 启用和禁用所需的 Angular JS

php - SQLSTATE[23000] : Integrity constraint violation: 1052 using join with laravel

javascript - 如何使用递归、rest/spread 运算符和解构将数组中的这些数字加倍?

ecmascript-6 - 谁能向我解释为什么以下两个箭头函数是等价的?

javascript - 如何使用条件进行对象解构?

php - 奇怪的 PHP 错误消息