tags:

views:

47

answers:

3

I've been having trouble searching for this answer because I am not quite sure how to phrase it. I am new to PHP and still getting my feet on the ground. I was writing a page with a class in it that had the property name. When I originally wrote the page there was no class so I just had a variable called $name. When I went to encapsulate it in a class I accidental changed it to be $myClass->$name. It tool me a while to realize that the syntax I needed was $myClass->name. The reason it took so long was the error I kept getting was "Attempt to access a null property" or something along those lines. The error lead me to believe it was a data population error.

My question is does $myClass->$name have a valid meaning? In other words is there a time you would use this and a reason why it doesn't create a syntax error? If so what is the semantic meaning of that code? When would I use it if it is valid? If its not valid, is there a reason that it doesn't create a syntax error?

+2  A: 

Yes.

$name = "bar";
echo $myClass->$name; //the same as $myClass->bar

I agree the error message is not very helpful.

Artefacto
So if I had a property on $myClass that was $bar then syntax would access it? I just want to make sure I'm clear about this. That makes sense though.
Craig Suchanec
yes. class Foo { public $bar; } $foo = new Foo(); $foo->bar = 3.1415926; $name = "bar"; echo $foo->$name; //Output: 3.1415926
dbemerlin
@ImperialLion You can also have a property named "$bar", but that would be strange, but possible, as in `$name = "\$bar"; $obj->$name = "foo"`.
Artefacto
Exactly the sort of insight I was looking for. I knew it had to be something I didn't understand with the semantics of the language. This really helps my understanding of the language. Thanks
Craig Suchanec
A: 

$myClass->$name is a "variable property name". It accesses the property whose name is in the variable $name as a string. The reason you were getting "null property" errors was that you didn't have a variable called $name (or it was null)

Matti Virkkunen
+1  A: 

Read about variable variables:

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Felix Kling