Search code examples
phpclassobjectparent

Does parent:: automatically determine class and object invoke context?


In first case we called function in object context. In second case we have class context. Does parent:: work like this and self simultaneously depending on the context?

class par_parent{
    private $var='value1';
    private static $val='value2';
    public function call(){
        var_dump('Object '.$this->var);
    }
    public static function staticCall(){
        var_dump('Static '.self::$val);
    }
}

class par_child extends par_parent{
    public function callObj(){
        parent::call();
    }

    public static function callStatic(){
        parent::staticCall();
    }
}



$obj=new par_child();
$obj->callObj();
**//string 'Object value1' (length=13)**
par_child::callStatic();
**//string 'Static value2' (length=13)**

Solution

  • The parent:: is binded like the self:: keyword, always sees the context where it have been defined code wise, not from where it's called, so in essence it works like the self:: keyword. If you need it to work like the $this use late static binding provieded static::. Consider this example:

    class A { 
        protected static $v = 'a';
        public static function staticsay() {
            print static::$v;
        }
    
    }
    class B extends A { 
        protected static $v = 'b';
        public static function say(){
            print parent::$v;
        }
    }
    class C extends B { 
        protected static $v = 'c';
        public static function selfsay(){
            print parent::$v;
        }
    } 
    
    C::say(); // prints 'a'
    C::selfsay(); // prints 'b'
    C::staticsay(); // prints 'c'
    

    Here we call the say() method on C it comes from the class B so it's parent:: means A and the A::$v is 'a' so it prints that.

    While the parent:: in C points to the class B and it sees it's $v as 'b'.

    With php 5.3 comes late static binding and the static:: keyword that lets you access the static variables and methods in baseclasses static methods so the A::staticsay will see the $v from the class C.