gpt4 book ai didi

php - 从父类调用扩展类函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:01:30 26 4
gpt4 key购买 nike

我是 OO PHP 的新手。有一些问题。

class a {
protected function a1() {
...
}
}

class b extends a {
public function b1() {
...
}
}

假设我们有 2 个类,如上所述。我正在调用 b 的方法,如下例所示

class a {
var $b;
function __construct()
{
$b = new b();
}
protected function a1() {
$b->b1();
}
}

class b extends a {
public function b1() {
...
}
}

我知道,可以从扩展类调用父类的方法,但我想知道是否可以反向调用?我的意思是,从父类内部调用扩展类方法(在本例中,class b 的方法来自 class a),而无需在 __contruct 中声明, 只需通过 $this->b();?

最佳答案

是的,您可以调用扩展类中的方法。

<?php
class a
{
public function a1 ()
{
$this->b1();
}

protected function b1()
{
echo 'This is in the a class<br />';
}
}

class b extends a
{
protected function b1()
{
echo 'This is in the b class<br />';
}
}

class c extends a
{
protected function b1()
{
echo 'This is in the c class<br />';
}
}

$a = new a();
$a->a1();

$b = new b();
$b->a1();

$c = new c();
$c->a1();
?>

这将导致:

This is in the a class
This is in the b class
This is in the c class

您可能还对抽象类感兴趣http://us3.php.net/manual/en/language.oop5.abstract.php

关于php - 从父类调用扩展类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8890054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com