我有两个类,它们具有几乎相同的方法,都称为 myMethod(),但是,myChild2::myMethod() 在其中有一行额外的代码,它使用了一个局部变量。我宁愿不在两个子类中复制代码。我想我可以将 myMethod 移动到 myParent,然后添加一个 if 语句来检测哪个子类正在调用该方法,但我猜这是不对的。最干净的方法是什么?谢谢
class myParent
{
    //code...
}
class myChild1 extends myParent
{
    public function myMethod()
    {
        // A bunch of code common to both myChild1::myMethod() and myChild2::myMethod() goes here
        // A bunch more code common to both myChild1::myMethod() and myChild2::myMethod() goes here
    }
}
class myChild2 extends myParent
{
    public function myMethod()
    {
        // A bunch of code common to both myChild1::myMethod() and myChild2::myMethod() goes here
        someOtherLineOfCode($someLocalVariable); // A single unique line of code goes here which uses a local variable
        // A bunch more code common to both myChild1::myMethod() and myChild2::myMethod() goes here
    }
}