如何在PHP子类中使用在父类中创建的对象


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

我有这段代码,我正在尝试使用对象

<?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 index() {
        $model = Model::get_estancia();
        $usuarios = $model->query("SELECT * FROM usuarios");
        $this->_view->set_params();   // cant be used.
        $this->load_view("index/index");
    }
}

我想使用setparms函数。但是我看不到View函数,所以我不能使用。有人能解释并建议我一个好的、安全的方法吗?

Phil的更正:如果找不到__construct()方法,PHP将恢复到旧的构造函数语法,并检查与对象同名的方法。在您的情况下,方法index()被视为构造函数,并阻止父级的构造函数将视图对象加载到$_view属性中。

通过在子类中定义__construct()并调用父类的构造函数,可以强制类继承父类的构造器:

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

这是固定代码:

<?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");
    }
}