当我在超类型中定义一个函数并且没有调用parent::时,它给了我一个错误,告诉我它是未定义的函数。我想知道我是否应该每次都使用parent::或者如果我在其他地方做错了什么。
我有一个名为core的类,它有一个用于转义字符串的escape()函数我试图从子类型调用这个函数。
现在我不认为静态方法是继承的。我用
调用所有静态超类方法parent::mystaticmethod()
。因为静态方法不能被继承。
仅当您要在子类中重写函数时才使用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