ItWorksOnLocal
ItWorksOnLocal

Reputation: 167

Calling a class name in other class's __constructor of the other class in php

my question is more of a theoretical or conceptual kind, i hope it's not a problem here. The thing is im new to OOP in PHP and also i've started to learn the MVC in php. i was going through an example and i found the following code. The thing that i cant understand is in the view construct function they have given the upper class name.. Whats that about?? i mean is it kind of extending the class or calling it or anything?? and doing this the called class(Model), does the view class gets the model class's variables and functions. and what does that mean $this->model->text ??? Thanks for any help..

<?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>';
    }
}
?>

Upvotes: 0

Views: 39

Answers (1)

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

public function __construct(Model $model) {
    $this->model = $model;
}

This means that the constructor accepts one argument that has to be an object of the type Model. If you pass anything else then you will get an error.

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

In the constructor the $model argument is saved to the private member $this->model. In the output() method that member is accessed ($this->model) and the text member is accessed from that ($this->model->text).

This is how you would use it:

// 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>

Upvotes: 1

Related Questions