PHPで親クラスのメソッドを呼び出す方法
PHPでは、親クラスのメソッドを呼び出す方法は2つあります。
- 保護者
- 親
- foo()
- 親::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()"
- これ
- これ
- 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` キーワードのどちらを使用するかは、親クラスのメソッドを呼び出すことができます。どちらを使用するかは、状況や各人の習慣によって異なります。