Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP7.0与5.6-数组键到对象的差异_Php_Arrays_Object_Key - Fatal编程技术网

PHP7.0与5.6-数组键到对象的差异

PHP7.0与5.6-数组键到对象的差异,php,arrays,object,key,Php,Arrays,Object,Key,问题: 为什么这段代码在php5.6和php7.0中运行时会产生不同的结果 背景 我有以下代码: <?php $assoc_array = [ 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4 ]; $index_array = ['a','b','c','d']; $object = new \StdClass; foreach($index_array as $item) { $objec

问题:


为什么这段代码在php5.6和php7.0中运行时会产生不同的结果

背景


我有以下代码:

<?php
$assoc_array = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 4
];
$index_array = ['a','b','c','d'];
$object = new \StdClass;

foreach($index_array as $item) {
    $object->$assoc_array[$item] = "";
}

print_r($object);
当我在相同的环境中运行它,但切换到php 5.6时,我得到以下结果:

Notice: Array to string conversion in /var/www/html/file.php on line 12
Notice: Array to string conversion in /var/www/html/file.php on line 12
Notice: Array to string conversion in /var/www/html/file.php on line 12
Notice: Array to string conversion in /var/www/html/file.php on line 12

stdClass Object ( 
    [Array] => Array ( 
        [a] => 
        [b] => 
        [c] => 
        [d] => 
    ) 
)
stdClass Object (
    [1] =>
    [2] =>
    [3] =>
    [4] =>
)
它并没有破坏我的代码,我只是很想知道为什么它不同,不知道从哪里开始我的研究


注意。这是我在这里感兴趣的对象,而不是通知-错误报告在这两者中都是打开的。

在PHP7中不能这样做:
$object->$assoc_数组[$item]=”
如您所见,您会收到一个通知,将您的代码替换为以下代码:

<?php
$assoc_array = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 4
];
$index_array = ['a','b','c','d'];
$object = new \StdClass;

foreach($index_array as $item) {
    $object->{$assoc_array[$item]} = "";
}

print_r($object);