Thursday, April 12, 2007

PHP object oddity

While writing about abstraction, I realized that since $variable->$something works, why shouldn't it work when $something=42? Well, logically, because $variable->42 won't work. It triggers a "Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$'" when attempted. However...

$a=1;
$b=new stdClass;
$b->$a='a';
var_dump($b);

...results in:

object(stdClass)#1 (1) {
  ["1"]=>
  string(1) "a"
}

Which, I suppose makes sense that PHP, in its type-cast-happy wisdom, would simply make it a string key. But it does create object variables only accessible through abstracting the variable key with another variable by using $b->$a. It will also cast an array to a key of "Array" without any of the array values, and it also triggers a notice about the Array to String conversion.

Just something I did not expect...

Then again, I also didn't expect the following to work in PHP 5.2.1:

function あ() {
 $い = 'あ';
 echo $い;
}
あ();

Labels: ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home