简体   繁体   中英

PHP - Extends class modify protect parent

I created an extended class in order to modify a protected var for particular purpose. However I don't understand how I can modify a parent class protected var from a child class and use it everywhere in the parent functions.

For example:

class parent {

    protected $data;

    public function __construct() {
        add_action('wp_ajax_output', array(&$this, 'output'));
    }

    public function output() {
        get_data();
        show();
    }

    public function get_data() {
        $this->$data = 'data_1';
    }


    public function show() {
        // here I'm using the protected var (I would like to use it from child)
        echo $this->data;
    }

}
new parent();

class child extends parent {


    public function __construct() {
        parent::__construct();
        add_action('wp_ajax_child_output', array(&$this, 'child_output'));
    }

    public function child_output() {
        $this->data = 'data_2';
        // I would like to use  $this->data in parent::show();
        parent::show();
    }

}
new child();

How can I override all protected var use in parent?

I've just tested your code and it gives out correct output. Issue lies somewhere else. when you use child_output() you use it correctly. All protected properties are accessible directly through a child class as well as all protected,public methods.

if you create an object from the parent class then you are using the parent class as it is. If you create an object from the child class then it inherits all properties and methods from the parent class, thus child class has a property $data and three extra methods

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