-1

当我在超类型中定义一个函数并在没有 parent:: 的情况下调用它时,它给了我并错误地告诉我它是未定义的函数。我想知道我是否应该每次都使用 parent:: 或者我是否在其他地方做错了什么。

我有一个名为 core 的类,它有一个用于转义字符串的 escape() 函数我试图从子类型中调用这个函数。 所有方法都是静态的。

现在我不认为静态方法是继承的。我将所有静态超类方法称为

parent::mystaticmethod() 

现在。因为静态方法不是继承的。

4

1 回答 1

4

parent::仅在您要覆盖子类中的函数时使用

解释这一点的最佳方法是这个例子:

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.
    }
}

实际示例(静态方法):

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!

无论如何,使用 parent:: 在非静态方法中更有用。

自 PHP 5.3.0 起,PHP 实现了一种称为后期静态绑定的功能,该功能可用于在静态继承的上下文中引用被调用的类。

更多信息在这里http://php.net/manual/en/language.oop5.late-static-bindings.php

于 2011-11-17T13:51:19.810 回答