在PHP中重写类中的函数
因此,我在一个PHP类中有一个函数,我希望为另一个类(扩展类)提供该函数的修改版本在PHP中重写类中的函数,php,class,oop,Php,Class,Oop,因此,我在一个PHP类中有一个函数,我希望为另一个类(扩展类)提供该函数的修改版本 我会在扩展类中用修改重新创建类吗?在我的扩展类中,如何让函数以不同的方式工作?您可以覆盖子类中的方法,如下所示: <?php class A { public function printText($param) { echo 'foo'; } } class B extends A { public function printText($param) {
我会在扩展类中用修改重新创建类吗?在我的扩展类中,如何让函数以不同的方式工作?您可以覆盖子类中的方法,如下所示:
<?php
class A {
public function printText($param) {
echo 'foo';
}
}
class B extends A {
public function printText($param) {
// Optional: This will call the printText method from the parent class A
parent::printText($param);
echo 'bar';
}
}
$instanceA = new A();
$instanceA->printText('sampleArg'); // Result: foo
$instanceB = new B();
$instanceB->printText('sampleArg'); // Result: foobar
/* EOF */
您可以覆盖子类中的方法,如下所示:
<?php
class A {
public function printText($param) {
echo 'foo';
}
}
class B extends A {
public function printText($param) {
// Optional: This will call the printText method from the parent class A
parent::printText($param);
echo 'bar';
}
}
$instanceA = new A();
$instanceA->printText('sampleArg'); // Result: foo
$instanceB = new B();
$instanceB->printText('sampleArg'); // Result: foobar
/* EOF */
因为在原始类中,函数应该以某种方式工作。在扩展类中,我想要一个稍有不同但基本相似的功能。@User016在OOP中覆盖函数是一个非常常见的需求,因为在原始类中,函数应该以某种方式工作。在扩展类中,我想要一个稍有不同但基本相似的功能。@User016覆盖OOPSo中的函数是一个非常常见的需要,因此类B将只输出“bar”?是的,仅bar
。您也可以在子方法中调用父方法。使用parent::printText('blah')
和方法B::printText
printsfoobar
;那么B类只会输出“bar”吗?是的,只有bar
。您也可以在子方法中调用父方法。使用parent::printText('blah')
和方法B::printText
printsfoobar
;