Skip to content

Instantly share code, notes, and snippets.

@rdoursenaud
Last active February 11, 2016 19:29
Show Gist options
  • Save rdoursenaud/224ac8dff52518402cc5 to your computer and use it in GitHub Desktop.
Save rdoursenaud/224ac8dff52518402cc5 to your computer and use it in GitHub Desktop.
Weird PHP7 behavior when calling class property from array key
<?php
// Run with PHP 5.x and 7.x to see the differences.
// SETUP
class Test {
var $property = 1;
}
$array = [
0 => 'property'
];
// Test
$test = new Test();
$result = $test->$array[0]; // PHP7: "Undefined property: Test::$Array"
var_dump($result);
// Expected $result == 1, got $result == null
// This is caused by a backward incompatible change introduced by the Uniform Variable Syntax RFC.
// See: https://wiki.php.net/rfc/uniform_variable_syntax#backward_incompatible_changes
// Workaround
// Be explicit about precedence
$result = $test->{$array[0]};
var_dump($result);
// $result == 1 as expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment