简体   繁体   中英

how to use objects created within the parent class in the child class PHP

I have this code and i´m trying to use a object

<?php

class Controller {

    public $_view;

    public function __construct() {
        $this->_view = new View();
        return $this->_view;

    }

}




class View {


    public $_params = array ();


    public function set_params($index_name,$valores) {
        $this->_params[$index_name] = $valores;
    }

    public function get_param($index_name){
        return $this->_params[$index_name];
    }
}

?>

i would like to do this:

class Index extends Controller {

    public function index() {
        $model = Model::get_estancia();
        $usuarios = $model->query("SELECT * FROM usuarios");
        $this->_view->set_params();   // cant be used.
        $this->load_view("index/index");

    }
}

i would like to use the set_parms function. but i can't see the View Function, then i can not use. Can someone explain and advise me a good and safe way?

Correction from Phil : If a __construct() method isn't found, PHP will revert to legacy constructor syntax and check for a method with the same name as the object. In your case the method index() is being treated as the constructor, and is preventing the parent's constructor from loading the view object into the $_view property.

You can force a class to inherit a parent's constructor by defining __construct() in the child and calling the parent's constructor:

public function __construct() {
    parent::_construct();
}

Here is the fixed code:

<?php

class Controller {

    public $_view;

    public function __construct() {
        $this->_view = new View();
        return $this->_view;

    }

}

.

class View {


    public $_params = array ();


    public function set_params($index_name,$valores) {
        $this->_params[$index_name] = $valores;
    }

    public function get_param($index_name){
        return $this->_params[$index_name];
    }
}

.

class Index extends Controller {
    public function __construct() {
        parent::__construct();
    }
    public function index() {
        $model = Model::get_estancia();
        $usuarios = $model->query("SELECT * FROM usuarios");
        $this->_view->set_params();   // cant be used.
        $this->load_view("index/index");

    }
}

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