简体   繁体   中英

A property exists in the parent class, but can't be used from the child class

EDIT: SOLVED!

I have been working on my own framework lately. I have a controller class like this:

class Controller {
    private $model;

    public function __construct() {
        global $bean_db, $mv_name;

        if (file_exists(APP_PATH . 'models/' . $mv_name . '.php')) {
            require APP_PATH . 'models/' . $mv_name . '.php';

            $model_name = $mv_name . '_Model';
            $model = new $model_name;
            $this->model = $model;
        }
    }
}

Now, in a specific controller file, I have code like this:

class Start_Controller extends Controller {
    function execute() {
        $this->model->exec("SET NAMES 'utf8'");
    }
}

As you may or may not expect, that did not work. I get an error message that the property named "model" does not exist. Can anyone help me solve this?

Because a private variable is limited to this class only and not to any children.
You need protected for this case

Make model protected rather than private . That's an immediate solution, but you may also want to re-work how your controllers access their models.

Private members are exclusive to the class in which they are declared. They can't be accessed anywhere else, even in subclasses.

You can overcome this in one of two ways.

  1. Make the private member protected
  2. Provide a protected getter for the private member

Normally you'd do the former, but there are cases where the latter may be a more sensible approach (if, for example, you need read-only access to the member).

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