在include /required文件中调用父函数


Call parent function inside included/required file

我想知道是否有可能在包含的文件中调用父文件的函数,以及如何工作

例如:

parent_file.php:

<?php
    if ( ! class_exists( 'Parent_Class' ) ) {
        class Parent_Class {
            public $id = 10;        

            public static function getInstance() {
                if ( ! ( self::$_instance instanceof self ) ) {
                    self::$_instance = new self();
                }
                return self::$_instance;
            }
            public function init() {            
                include 'child-file.php';
                $child = new Child_Class($id);
                $child->action();
            }
            public function edit($values_of_id) {
                return $values_of_id;
            }
    ?>


child_file.php:

<?php
    if ( ! class_exists( 'Child_Class' ) ) {
        class Child_Class {
            private $id;
            function __construct(){
                $params = func_get_args();
                    if(!empty($params))
                        foreach($params[0] as $key => $param)
                                if(property_exists($this, $key))
                                    $this->{$key} = $param;
                    parent::__construct( array(
                        'id'  => $this->id,
                ) );
            }
            public function action() {
                $url = 'http://myserver.com/edit_child.php?page='. $_REQUEST['page'] .'&action=select&id='. absint($this->id) ) );
                $action = '<a href='. $url .'>Edit</a>'         
                return $action;
            }   
            public function select_table_row() {
                if ( isset( $_GET['action'] ) && !empty( $_GET['action'] ) )
                    $row = $_GET['id'];
                $connection = new mysqli($servername, $username, $password, $dbname); // fictitious params
                $query = "SELECT * FROM MyTable WHERE id = $row";
                $values_of_id = mysqli_query($connection, $query);
                // Call function of parent_file.php
                edit($values_of_id);
            }
            $this->select_table_row();
    ?>

这是一个虚构的例子,我知道代码不能这样工作。我只是想针对我的问题,让我的想法可视化,也许更容易理解。

重要的是,我不能在我的child_file.php中包含parent_file.php,因为Child_Class可以从多个文件访问。

如果这个问题已经问过了,我很抱歉。关于这个话题,我的流行语有限,找不到这样的东西。

必须将父类对象传递给子类,如下所示:

class parentClass {
    private $str;
    public function __construct($str){
        $this->str = $str;
    }
    public function getChild() {
        $obj = new childClass($this);
        $obj->callParent("send");
    }
    public function send() {
        echo $this->str;
    }
}
class childClass {
    private $parent;
    public function __construct($parent) {
        $this->parent = $parent;
    }
    public function callParent($method) {
        return $this->parent->$method();
    }
}
$obj = new parentClass("hello");
$obj->getChild(); // prints "hello"

演示:https://eval.in/403427