在 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 开始,这是可能的:
You can now specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys.
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/