2

The following code works fine in php 5.3.3 but failed when I upgraded to 7. I use this construct a lot and shudder to think I have to change it everywhere.

<?php
$a=array();
$a['one']='uno';
$a['two']='dos';
$b=new stdClass();
$b->uno=1;
$b->dos=2;
$b->$a['two']=3;
print_r($b);
print "\n";

It prints PHP Notice: Array to string conversion in /home/gaares/a.php on line 8

stdClass Object
(
    [uno] => 1
    [dos] => 2
    [Array] => Array
        (
            [two] => 3
        )

)

on PHP 7 and prints

stdClass Object
(
    [uno] => 1
    [dos] => 3
)

On PHP 5.

Is there any way I can encourage PHP 7 to dereference the array and use the value of $a['two'] instead of stopping the scan at the array? I use this construct in Waaayyyy too many places to want to change the code to

<?php
$a=array();
$a['one']='uno';
$a['two']='dos';
$b=new stdClass();
$b->uno=1;
$b->dos=2;
$c=$a['two'];
$b->$c=3;
print_r($b);
print "\n";

Which makes it do what I expect.

2
  • 3
    $b->{$a['two']} = 3; Commented Jul 23, 2018 at 11:14
  • The use of curly braces fixed the problem. I don't look forward to fixing this in dozens of cases over multiple projects, however. Commented Jul 23, 2018 at 19:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.