10

I am a newbie of PHP. I study it from php.net, but I found a problem today.

class foo {
    var $bar = 'I am bar.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}\n";
echo "{$foo->$baz[1]}\n";

The documentation(http://php.net/manual/en/language.types.string.php) say that the above example will output:

I am bar.
I am bar.

But I get the different output run on my PC(PHP 7):

I am bar.
<b>Notice</b>:  Array to string conversion in ... on line <b>9</b><br />
<b>Notice</b>:  Undefined property: foo::$Array in ... on line <b>9</b><br />

Why?

lizs
  • 540
  • 2
  • 8
  • 18
  • 1
    The reference to **People** in the error message, but absence **People** in the code is confusing to say the least. – user2182349 Mar 10 '16 at 02:52
  • 1
    Here are the official documentation on [the changes](http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.indirect) – Michael Mar 10 '16 at 03:32

2 Answers2

28

This should work with PHP 7:

class foo {
var $bar = 'I am bar.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}\n";
echo "{$foo->{$baz[1]}}\n";

This is caused because in PHP 5 the following line:

echo "{$foo->$baz[1]}\n";

is interpreted as:

echo "{$foo->{$baz[1]}}\n";

While in PHP 7 it's interpreted as:

echo "{{$foo->$baz}[1]}\n";

And so in PHP 7 it's passing the entire array to $foo instead of just that element.

C.Liddell
  • 1,084
  • 10
  • 19
0

Just assign array to a variable and use that variable on function call. That will work... I fixed this issue in that way.

Because when coming to PHP 7, that will pass whole array when we directly used it on function call.

EX:

$fun['myfun'](); // Will not work on PHP7.

$fun_name = $fun['myfun'];
$fun_name();    // Will work on PHP7.
DaFois
  • 2,197
  • 8
  • 26
  • 43
Ramasamy Kasi
  • 171
  • 3
  • 3