简体   繁体   中英

Accessing child class data from parent class with PHP OOP

I want to add some data form child class to parent class using the same method and also want to retrieve the data. Please check the example code that will help you for better understanding.

class HTML{

    public function add_control(){

    }

    public function all_controls(){

    }

}

class Control1 extends HTML
{

    public function register_controls()
    {

        $this->add_control([
            'name' => 'a',
            'label' => 'A',
        ]);

        $this->add_control([
            'name' => 'b',
            'lable' => 'B',
        ]);
    }

}

class Control2 extends HTML{

    public function register_controls()
    {

        $this->add_control([
            'name' => 'c',
            'label' => 'C',
        ]);


    }
}

(new HTML)->all_controls();

Sample Output ['a','b','c'] I hope you got my point.

I am assuming that your data is in a class variable. I didn't quite understand your point. It is not really possible to get the data of the child... It would be possible with a static class variable but then you won't be able to use $this in the add_control($data) function. All data will then be stored in one variable which is shared by all the three classes. This is my approach to your problem, I hope it solves your question.

<?php

class HTML{
    protected static $data;

    public function add_control($data) {
        self::$data[] = $data;
    }

    public function all_controls() {
        var_dump(self::$data);
    }

}

class Control1 extends HTML
{

    public function register_controls() {

        $this->add_control([
            'name' => 'a',
            'label' => 'A',
        ]);

        $this->add_control([
            'name' => 'b',
            'lable' => 'B',
        ]);
    }

}

class Control2 extends HTML{

    public function register_controls() {
        $this->add_control([
            'name' => 'c',
            'label' => 'C',
        ]);
    }
}
$html = new HTML();
$control1 = new Control1();
$control2 = new Control2();
$control1->register_controls();
$control2->register_controls();
$html->all_controls();
?>

Edit:
After the hint of Markus Zeller... you can also make the all_controls() function static. Then there will be no need to create an object of the class HTML. If this will suit your problem.

class HTML {

public static function all_controls() {
      var_dump(self::$data); //or any other echo method
}

}
//other stuff...
$control1->register_controls();
$control2->register_controls();
HTML::all_controls(); //no object of HTML necessary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM