共计 756 个字符,预计需要花费 2 分钟才能阅读完成。
在 PHP 中,调用父类的方法有两种方法:
- 使用
parent关键字:
可以使用parent关键字来调用父类的方法。例如,如果子类继承了父类的方法foo(),可以使用parent::foo()来调用父类的foo()方法。
class ParentClass {protected function foo() {echo "ParentClass foo()";
}
}
class ChildClass extends ParentClass {public function foo() {parent::foo(); // 调用父类的 foo()方法
echo "ChildClass foo()";
}
}
$child = new ChildClass();
$child->foo(); // 输出:"ParentClass foo() ChildClass foo()"
- 使用
$this关键字:
在子类中,可以使用$this关键字来调用父类的方法。例如,如果子类继承了父类的方法foo(),可以使用$this->foo()来调用父类的foo()方法。
class ParentClass {protected function foo() {echo "ParentClass foo()";
}
}
class ChildClass extends ParentClass {public function foo() {$this->foo(); // 调用父类的 foo()方法
echo "ChildClass foo()";
}
}
$child = new ChildClass();
$child->foo(); // 输出:"ParentClass foo() ChildClass foo()"
无论使用 parent 关键字还是 $this 关键字,都可以调用父类的方法。选择哪种方式取决于具体的情况和个人习惯。
丸趣 TV 网 – 提供最优质的资源集合!
正文完
发表至: PHP
2023-12-12