<?php
class X {
    function foo() {
        echo "Class Name:".get_class($this)."<br>"; //it displays Y... :)
        echo get_class($this)::$public_var; //not working
        echo Y::$public_var; //works
        Y::y_method();  //works
        get_class($this)::y_method(); //not working
        $classname = get_class($this);
        $classname::y_method(); // again not working..  :( 
    }
    function bar() {
        $this->foo();
    }
}
class Y extends X {
    public static $public_var = "Variable of Y Class";
    public function y_method()
    {
        echo "Y class method";
    }
}
$y = new Y();
$y->bar();
?>
my only question is how to get access members of y class only with dynamically providing class name without changing current structure.
            Asked
            
        
        
            Active
            
        
            Viewed 420 times
        
    0
            
            
        - 
                    1get_class() will always return X. $this is not set in a static function. enable errors and read the log to learn. you might be looking for `get_called_class()` instead. – hakre Jul 18 '11 at 09:27
 - 
                    possible duplicate of [How do I call a static child function from parent static function ?](http://stackoverflow.com/questions/6678466/how-do-i-call-a-static-child-function-from-parent-static-function) – hakre Jul 18 '11 at 09:28
 - 
                    1Thanx binaryLV i have changed variable name. – hardik Jul 18 '11 at 10:10
 - 
                    hakre - > get_class() is returning class name Y, pls check your self – hardik Jul 18 '11 at 10:28
 
1 Answers
4
            
            
        You are looking for get_called_class()
class X {
    function foo() {
    $that = get_called_class();
        echo $that::$private_var;
        echo $that::y_method();
    }
    function bar() {
        $this->foo();
    }
}
class Y extends X {
    public static $private_var = "Variable of Y Class";
    public function y_method()
    {
        echo "Y class method";
    }
}
$y = new Y();
$y->bar();
        Stoosh
        
- 2,408
 - 2
 - 18
 - 24