父方法的PHP代码添加到具有工作返回语句的子方法中


PHP code of parent method add to child method with working return statement

我有BaseClass。我有一个方法BaseMethod,它有一些if.else结构。

我想在子方法中使用BaseMethod的if.else,以避免代码重复。

但当我使用parent::BaseMethod()时,我没有收到理想的结果,因为BaseMethod(()的return不起作用。

换句话说,我想把函数串在一起。如果父方法没有进行计算以返回结果,我想继续到子方法

示例,我想要的:

class BaseClass
{
    public function BaseMethod($baseVariable)
    {
        if($baseVariable == 1) {
           return 'something'; // I want this work in my base method
        }
    }
}
class ChildClass extends BaseClass
{
    public function BaseMethod($baseVariable)
    {
        parent::BaseMethod($baseVariable);
        if($baseVariable == 3) {
           return 'one more something';
        }
    }
}
$a = new BaseClass();
$b = new ChildClass();
echo $a->baseMethod(1); // this is work
echo $b->baseMethod(1); // this is not work

请帮我完成这项任务。非常感谢您的帮助!

更新我已经编辑了我的代码,您可以在您的环境中进行测试。

如果$baseVariable == 3,则返回一些东西,如果不是,则返回父方法:

class ChildClass extends BaseClass
{
    public function BaseMethod($baseVariable)
    {
        if($baseVariable == 3) {
           return 'one more something';
        } else {
           return parent::BaseMethod($baseVariable);
        }
    }
}

不确定您要如何处理此签名:public function method BaseMethod($baseVariable)。你觉得method是一个关键词吗?你是否试图像扩展类一样扩展函数?

这不是有效的PHP语法。以下编辑后的代码可以"工作":

class BaseClass
{
    public function baseMethod($baseVariable)
    {
        if($baseVariable == 1) {
           return 'something'; // I want this work in my base method
        } elseif (2==1) {
           return 'something else'; // This too
        }
        return null;
    }
}
class ChildClass extends BaseClass
{
    public function baseMethod($baseVariable)
    {
        $foo = parent::baseMethod($baseVariable);
        if (!is_null($foo)) return $foo;
        if($baseVariable == 3) {
           return 'one more something';
        } else {
           return 'one more something else';
        }
    }
}
$a = new BaseClass();
$b = new ChildClass();
echo $a->baseMethod(1); // this is work
echo $b->baseMethod(1); // this is not work, because "1" using in parent::baseMethod()

好。请参阅更新的代码很难理解你的要求。我想我现在明白了。