Php 如何共享父类';逻辑和功能?
我想向父类添加其他内容。 我无法修改父类,因为软件升级时所有修改都将被删除。所以我想扩展这个类。我可以在不重复父函数的情况下将其添加到子类中吗Php 如何共享父类';逻辑和功能?,php,class,Php,Class,我想向父类添加其他内容。 我无法修改父类,因为软件升级时所有修改都将被删除。所以我想扩展这个类。我可以在不重复父函数的情况下将其添加到子类中吗 class parent { public function __construct() { // lots of logic to hook up following functions with main software } // lots of parent functions } clas
class parent
{
public function __construct()
{
// lots of logic to hook up following functions with main software
}
// lots of parent functions
}
class child extends parent
{
function __construct()
{
// Is this going to share parent's logic and hook up with those actions?
// Or, should I repeat those logics?
parent::__construct();
// add child addicional logic
}
// child functions
// should I repeat parent's functions? I need the parent take child along all the jobs.
}
是的,这是正确的方法
class parent
{
public function __construct()
{
// lots of logic to hook up following functions with main software
}
// lots of parent functions
protected function exampleParentFunction()
{
//do lots of cool stuff
}
}
class child extends parent
{
function __construct()
{
// This will run the parent's constructor
parent::__construct();
// add child additional logic
}
// child functions
public function exampleChildFunction();
{
$result = $this->exampleParentFunction();
//Make result even cooler :)
}
//or you can override the parent methods by declaring a method with the same name
protected function exampleParentFunction()
{
//use the parent function
$result = parent::exampleParentFunction();
//Make result even cooler :)
}
}
根据您最近提出的问题,您确实需要阅读一本关于PHP OOP的书。从手册开始是的,正如vascowhite所说,这是正确的方法。
至于重复父函数,您不必这样做,除非您也想向这些函数添加额外的逻辑。e、 g
class foo {
protected $j;
public function __construct() {
$this->j = 0;
}
public function add($x) {
$this->j += $x;
}
public function getJ() {
return $this->j;
}
}
class bar extends foo {
protected $i;
public function __construct() {
$this->i = 0;
parent::__construct();
}
public function add($x) {
$this->i += $x;
parent::add($x);
}
public function getI() {
return $this->i;
}
// no need to redo the getJ(), as that is already defined.
}
您只需要覆盖更改的零件。如果除了附加代码之外还需要执行父代码,则只需调用父代码::*。因此,如果您还希望执行父类中的逻辑,那么对于您的ctor,您需要调用
parent::\u construct()
。如果你不想让它们过载,你不需要从父级添加任何方法。太好了!这正是我想做的谢谢你的建议。遇到问题时,我一直在php手册中搜索函数,没有花时间仔细研究。也许是时候做这项艰巨的任务了。