I having a problem accessing a class variable from nested function with in one of the classes.. Here is a example: class varscope { private $myvar = "Hello!"; public function echo_from_nested() { function nested() { echo("Nested :".$this->myvar."<br>"); } echo("Not Nested :".$this->myvar."<br>"); nested(); } } $test = new varscope(); $test->echo_from_nested(); Code (markup): Is there anyway to access that class variable with out passing it through the function?
What is the output? Try putting public in front of the function nested(). Not sure, it looks ok but I'm probably missing something.
I don't think it's possible without passing it. Why would you ever want to nest functions in classes?
Doctor, it hurts when I nest functions. "Well then don't nest functions." The reason you are getting an error is that the nested function is defined as a global function, not as a method of your class. So, $this does not exist inside your nested function. What you are writing is exactly the same as: function nested() { echo("Nested :".$this->myvar."<br>"); } class varscope { private $myvar = "Hello!"; public function echo_from_nested() { echo("Not Nested :".$this->myvar."<br>"); nested(); } } $test = new varscope(); $test->echo_from_nested(); PHP:
That makes sense Selkirk. I didn't think of it like that, but now that you mention it ... it totally makes sense. +1 from me.