Skip to content
Advertisement

How view file get the variable from controller?

I’m a student and new to PHP. After searching a lot i still don’t understand how the view file got the variable from controller. I got the function view() from Controller.php class.

public function view($view, $data=[])
    {
        require_once "./mvc/views/".$view.".php";
    }

And i got a HomeController.php Extends the Controller

function toTheView($x,$y){
        $model = $this->model("User");
        $sum = $model->Sum($x,$y);
        $this->view("calc", compact('sum'));
    }

This is inn my calc.php view file.

<h3><?php echo $data["sum"]; ?></h3>

As you can see that the calc.php doesn’t require any file from Controller.php or HomeController.php but how it’s still can show that variable out? My IDE show the red alert on that line in calc.php but its still working.

Thank you for helping me.

Advertisement

Answer

Your require_once includes content of file in that place, so your view fiel can access any variables in same scope, so it can use passed variables from public function view($view, $data=[]) and also access $this.

In the end your code looks like this:

public function view($view, $data=[])
    {
        // after executing: require_once "./mvc/views/".$view.".php";
       <h3><?php echo $data["sum"]; ?></h3>
    }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement