PHP Class Scope Problem

Discussion in 'PHP' started by DLWood, May 23, 2006.

  1. #1
    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?
     
    DLWood, May 23, 2006 IP
  2. Slapyo

    Slapyo Well-Known Member

    Messages:
    266
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    108
    #2
    What is the output?

    Try putting public in front of the function nested().

    Not sure, it looks ok but I'm probably missing something.
     
    Slapyo, May 23, 2006 IP
  3. Young Twig

    Young Twig Peon

    Messages:
    27
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I don't think it's possible without passing it.

    Why would you ever want to nest functions in classes? :confused:
     
    Young Twig, May 23, 2006 IP
  4. Selkirk

    Selkirk Peon

    Messages:
    93
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #4
    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:
     
    Selkirk, May 23, 2006 IP
    Slapyo likes this.
  5. Slapyo

    Slapyo Well-Known Member

    Messages:
    266
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    108
    #5
    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.
     
    Slapyo, May 23, 2006 IP