Why does isset()
not work when the property names are in variables?
$Object = new stdClass();
$Object->tst = array('one' => 1, 'two' => 2);
$tst = 'tst'; $one = 'one';
var_dump( $Object, isset( $Object->tst['one'] ), isset( $Object->$tst[ $one ] ) );
outputs the following:
object(stdClass)#39 (1) {
["tst"]=>
array(2) {
["one"]=>
int(1)
["two"]=>
int(2)
}
}
bool(true)
bool(false) // was expecting true here..
Edit: went on toying around with the code, and found out that
var_dump( $Object->$tst['one'] );
outputs a Notice:
E_NOTICE: Undefined property: stdClass::$t
So I think the problem is that the $tst[...]
part is evaluated in 'string mode' (evaluating to the first character in the string; in this case "t"), before going onto fetching the property from the object;
var_dump( $tst, $tst['one'] ); // string(3) "tst" string(1) "t"
Solution: is to put braces around the variable name ($this->{$tst}
), to tell the interpreter to retrieve its value first, and then evaluate the [...]
part:
var_dump( $Object->{$tst}['one'] ); // int(1) yay!
Try adding braces around the property name...
isset( $Object->{$tst}[ $one ] );
CodePad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With