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 开发者_如何学Pythonmeaning? 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?
Yes.
$name = "bar";
echo $myClass->$name; //the same as $myClass->bar
I agree the error message is not very helpful.
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.
$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
)
精彩评论