2

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?

3 Answers 3

3

Yes.

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

I agree the error message is not very helpful.

4
  • 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. Commented Jun 9, 2010 at 12:11
  • yes. class Foo { public $bar; } $foo = new Foo(); $foo->bar = 3.1415926; $name = "bar"; echo $foo->$name; //Output: 3.1415926 Commented Jun 9, 2010 at 12:14
  • 1
    @ImperialLion You can also have a property named "$bar", but that would be strange, but possible, as in $name = "\$bar"; $obj->$name = "foo". Commented Jun 9, 2010 at 12:16
  • 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 Commented Jun 9, 2010 at 12:21
2

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.

0

$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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.