Skip to content

Instantly share code, notes, and snippets.

@binarycleric
Created October 12, 2012 17:26
Show Gist options
  • Save binarycleric/3880369 to your computer and use it in GitHub Desktop.
Save binarycleric/3880369 to your computer and use it in GitHub Desktop.
PHP Bug #55021 Investigation
<?php
/*
* I looked into this for a bit and I must say I was a bit confused
* until the answer smacked me in the face.
*
* The 'fn3' isn't doing what you think it's doing. Upon glancing at
* the code it may appear that $this->a['first'] is having the value
* 'foo' appended to it (which doesn't make sense because
* $this->a['first'] is a string, not an array).
*
* What is actually happening (according to my tests on PHP 5.2.17) is
* that $b[$k][] is being evaluated first and then the result is being
* used at the property name, which explains the "Cannot use [] for
* reading" error.
*
* Assuming your test code was changed and $this->a['first'] was an
* array, the "slightly more correct" way would be to call
* $this->{$b}[$k][] which would evaluate to $this->a['first'][].
*
* In my opinion this should be classified as "not a bug". * I looked into this for a bit and I must say I was a bit confused
* until the answer smacked me in the face.
*
* The 'fn3' isn't doing what you think it's doing. Upon glancing at
* the code it may appear that $this->a['first'] is having the value
* 'foo' appended to it (which doesn't make sense because
* $this->a['first'] is a string, not an array).
*
* What is actually happening (according to my tests on PHP 5.2.17) is
* that $b[$k][] is being evaluated first and then the result is being
* used at the property name, which explains the "Cannot use [] for
* reading" error.
*
* Assuming your test code was changed and $this->a['first'] was an
* array, the "slightly more correct" way would be to call
* $this->{$b}[$k][] which would evaluate to $this->a['first'][].
*
* In my opinion this should be classified as "not a bug".
*/
function derp() {
$herp = TRUE;
return ($herp == TRUE) ? TRUE : FALSE;
}
derp();
exit();
class C
{
public $a = array('first' => 'baz');
/**
* This case is most interesting, because as it run parse error
* @note don't parse $this->$b
*/
public function fn3($k)
{
$b = 'a';
$this->{$b}[$k] = array();
$this->{$b}[$k][] = 'foo'; ///BUG Error parse : PHP Fatal error: Cannot use [] for reading in ....
}
/**
* Solution for fix fn3
*/
public function fn4($k)
{
$b = 'a';
$tmp =& $this->$b;
$tmp[$k][] = 'foo';
}
}
$obj = new C;
$obj->fn3('first');
var_export($obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment