Php 不允许子类调用受保护属性的方法
我正在使用MVC概念开发应用程序,希望限制View类调用模型的方法,但允许它访问模型的属性,这样它就可以在需要时获取数据。相反,我想让控制器类能够调用模型的方法,如果可能的话,限制它访问属性,因为它确实不需要这样做。 我的问题是如何设计类关系来实现这个目标,或者我可以告诉php不允许另一个类的类调用方法吗? 当前我的类的关系如下所示: 控制器 看法 还有其他从Controller和View类继承的类,如:Php 不允许子类调用受保护属性的方法,php,class,oop,inheritance,encapsulation,Php,Class,Oop,Inheritance,Encapsulation,我正在使用MVC概念开发应用程序,希望限制View类调用模型的方法,但允许它访问模型的属性,这样它就可以在需要时获取数据。相反,我想让控制器类能够调用模型的方法,如果可能的话,限制它访问属性,因为它确实不需要这样做。 我的问题是如何设计类关系来实现这个目标,或者我可以告诉php不允许另一个类的类调用方法吗? 当前我的类的关系如下所示: 控制器 看法 还有其他从Controller和View类继承的类,如: class UserController extends Controller { p
class UserController extends Controller
{
public function modifyData()
{
$this->_model->modifyX(1); //this works and it should be working because i need the controller to be able to call model's methods
$someVar = $this->_model->x; //this works and it should not be working because i don't need the controller to be able to get model's properties
}
}
及
那么,您认为实现这一点的最佳方法是什么呢?忽略MVC结构是否是正确的软件设计,您可以通过只向类提供它们所需的数据来解决问题。例如,如果希望视图只能访问模型的属性,则不要将模型作为参数实例化视图,而只将数据从模型传递到视图
class View
{
protected $_model; //has access to model so it can get model's properties when needed
public function __construct($model)
{
$this->_model = $model;
}
}
class UserController extends Controller
{
public function modifyData()
{
$this->_model->modifyX(1); //this works and it should be working because i need the controller to be able to call model's methods
$someVar = $this->_model->x; //this works and it should not be working because i don't need the controller to be able to get model's properties
}
}
class UserView extends View
{
public function getData()
{
$this->_model->modifyX(1); //this works and it should not be working because i don't need the view to be able to call model's methods
$someVar = $this->_model->x; //this works and it should be working because i do need the view to be able to get model's properties
}
}