【问题标题】:Calling a class name in other class's __constructor of the other class in php在php中另一个类的其他类的__constructor中调用一个类名
【发布时间】:2015-11-01 00:46:12
【问题描述】:

我的问题更多是理论上或概念上的,我希望这不是问题。这件事对 PHP 中的 OOP 来说是新手,而且我已经开始学习 php 中的 MVC。我正在浏览一个示例,我发现了以下代码。我无法理解的是在视图构造函数中他们给出了上层类的名称。那是怎么回事? 我的意思是它是扩展类还是调用它或其他什么?并且这样做被调用的类(模型),视图类是否获取模型类的变量和函数。那是什么意思 $this->model->text ??? 感谢您的帮助..

<?php
class Model {
    public $text;
    public function __construct() {
        $this->text = 'Hello world!';
    }        
}
class View {
    private $model;
    public function __construct(Model $model) {
        $this->model = $model;
    }
    public function output() {
        return '<h1>' . $this->model->text .'</h1>';
    }
}
?>

【问题讨论】:

    标签: php oop model-view-controller


    【解决方案1】:
    public function __construct(Model $model) {
        $this->model = $model;
    }
    

    这意味着构造函数接受一个参数,该参数必须是Model 类型的对象。如果你传递其他任何东西,那么你会得到一个错误。

    public function output() {
        return '<h1>' . $this->model->text .'</h1>';
    }
    

    在构造函数中,$model 参数被保存到私有成员 $this-&gt;model。在output() 方法中,访问该成员($this-&gt;model)并从该方法访问text 成员($this-&gt;model-&gt;text)。

    这就是你将如何使用它:

    // Create an instance of the Model class
    $myModel = new Model();
    
    // Create an instance of the View class, passing the
    // previously created Model instance as the argument
    $myView = new View($myModel);
    
    // Call the output method which accesses $myModel in
    // order to get the "text" member
    echo $myView->output(); // <h1>Hello world!</h1>
    

    【讨论】:

    • 帮助了...干杯!!
    猜你喜欢
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多