Php 如何在父类的子类中调用重写的方法
我有课Php 如何在父类的子类中调用重写的方法,php,class,overriding,Php,Class,Overriding,我有课 class foo { function do_something() { load(); } function load() { //things echo 'load from foo'; } } 和另一个扩展foo的类(子类): 然后: $obj = new bar(); 我想知道的是,我如何调用$obj->do_something(),以便该方法使用子“load”方法,而不是foo类中声明的方法 因此,我希望输出为: $ob
class foo {
function do_something() {
load();
}
function load() {
//things
echo 'load from foo';
}
}
和另一个扩展foo的类(子类):
然后:
$obj = new bar();
我想知道的是,我如何调用$obj->do_something()
,以便该方法使用子“load”方法,而不是foo类中声明的方法
因此,我希望输出为:
$obj->do_something();
输出:load from bar(子项)
这在PHP中是可能的吗
谢谢 试试这个
class foo {
function do_something() {
static::load();
}
function load() {
//things
echo 'load from foo';
}
}
class bar extends foo {
function load() {
//things
echo 'load from bar (child)';
}
}
$obj = new bar;
$obj->do_something();
如果您想拥有如此紧密的方法耦合,我建议您使用抽象函数。它需要很高的维护,并且在类之间创建了一些紧密的耦合 我建议在父级中创建一个抽象函数,每个子级都将使用自己的逻辑来实现 即使这样,如果您想将父类函数更改为
function do_something(){
if(method_exists($this, 'test')){
$this->test();
}
}
您需要使用
$this
限定对象上下文。与其他一些语言不同,PHP要求使用$this
显式限定实例,以用于对象中的所有方法调用
class foo {
function do_something() {
// load();
$this->load();
}
function load() {
echo 'load from foo';
}
}
class bar extends foo {
function load() {
echo 'load from bar (child)';
}
}
$obj = new bar();
$obj->do_something();
在您的代码中(仅调用load()
),该语言正在寻找一个名为load
的全局定义函数,该函数当然不起作用(或者在更糟的情况下,可能不正确)
正如另一个答案所指出的,您必须通过使用self
或static
(我建议您继续阅读以了解绑定差异)来对静态方法进行类似的限定
从继承类中,在重写方法中,您还可以使用parent
调用方法的父类定义:
class bar extends foo {
function load() {
parent::load(); // right here
echo 'load from bar (child)';
}
}
这将调用父类版本的加载方法,并继续执行子类的定义。您可以使用抽象类和抽象方法:
abstract class Foo{
function test() {
$this->method();
}
abstract function method();
}
class Test extends Foo {
function method() {
echo 'class Test';
}
}
$test = new Test();
$test->test();
这“有效”,但我不建议这样做,因为使用
static
解析方法调用可能会在给定的静态上下文中导致非常混乱的错误,而$This
总是正确解析到当前实例;出于某种原因,您是否建议使用static
代替$this
更可取?
abstract class Foo{
function test() {
$this->method();
}
abstract function method();
}
class Test extends Foo {
function method() {
echo 'class Test';
}
}
$test = new Test();
$test->test();