When I extend a class, do I call the static functions directly from a subtype or should I use parent:: each time?

StackOverflow https://stackoverflow.com/questions/8168136

Question

When I defined a function in a supertype and called without parent:: it gave me and error teling me it's undefined function. I am wondering if I should use parent:: each time or if I am doing something wrong somewhere else.

I have a class, named core, which has an escape() function for escaping strings I am trying to call this function from subtypes. all methods are static.

Right now I don'T think static methods are inherited. I call all the static superclass methods with

parent::mystaticmethod() 

now. Because static methods are not inherited.

Was it helpful?

Solution

use parent:: only when you are going to override function in your child class

Best way to explain this is this example:

class Parent {
    function test1() {}    
    function test2() {}
    function __construct() {}
}

class Child extends Parent {
    function test1() {}  // function is overrided
    function test3() {
        parent::test1(); // will use Parent::test1()
        $this->test1();  // will use Child::test1()
        $this->test2();  // will use Parent:test2()
    }
    function __construct() {
        parent::__construct() // common use of parent::
        ... your code.
    }
}

Practical example (static methods):

class LoaderBase {
    static function Load($file) {
        echo "loaded $file!<br>";
    }
}

class RequireLoader extends LoaderBase {
    static function Load($file) {
        parent::Load($file);
        require($file);
    }
}

class IncludeLoader extends LoaderBase {
    static function Load($file) {
        parent::Load($file);
        include($file);
    }
}

LoaderBase::Load('common.php'); // this will only echo text
RequireLoader::Load('common.php'); // this will require()
IncludeLoader::Load('common.php'); // this will include()

Output:
loaded common.php!
loaded common.php!
loaded common.php!

Anyways using parent:: is more useful in non-static methods.

As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.

More information here http://php.net/manual/en/language.oop5.late-static-bindings.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top