从父类调用子方法

Dav*_*ard 3 php class

我有一个类被其他几个类用作扩展器,在一个实例中,父类的方法需要从子类回调一个方法.有办法做到这一点吗?

我意识到PHP包含abstract类和函数,但是要求每个子类都具有声明的abstract函数,在这种情况下我不需要.

例如(这些是例子,而不是现实生活) -

Class parent{

    function on_save_changes(){

        some_parent_function();

        if($_POST['condition'] === 'A') :
            // Call 'child_1_action()'
        elseif($_POST['condition'] === 'B') :
            // Call 'child_2_action()'
        endif       

        some_other_parent_function();

    }

    function some_parent_function(){
        // Do something here, required by multiple child Classes
    }

}

Class child_1 Extends parent{

    function __construct(){
        $this->on_save_changes();
    }

    function child_1_action(){
        // Do something here, only every required by this child Class
    }

}

Class child_2 Extends parent{

    function __construct(){
        $this->on_save_changes();
    }

    function child_2_action(){
        // Do something here, only every required by this child Class
    }

}
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 7

您只需调用子方法即可完成此操作,例如:

if($_POST['condition'] === 'A') :
    $this->some_parent_function();
    $this->child_1_action();
Run Code Online (Sandbox Code Playgroud)

但是,你应该避免这样做.将检查放在调用仅存在于子类中的方法的父项中是一种非常糟糕的设计气味.通过利用众所周知的设计模式或简单地通过更好地思考类层次结构,总有一种方法可以以更有条理的方式进行.

您可以考虑的一个非常简单的解决方案是在父类中将所有这些方法实现为no-ops; 每个子类都可以覆盖(并提供实现)它感兴趣的方法.这是一个有点机械的解决方案,因此无法知道它是否确实是您的情况下的最佳方法,但即使如此,它也比冷调用好得多技术上不保证存在的方法.