Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isset() with dynamic property names

Tags:

oop

php

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!
like image 973
Rijk Avatar asked Sep 05 '11 11:09

Rijk


1 Answers

Try adding braces around the property name...

isset( $Object->{$tst}[ $one ] );

CodePad.

like image 55
alex Avatar answered Nov 08 '22 10:11

alex