2

i'm building a simple php MVC with MVC basic concept

while building the view class i tried to built a simple function which let me pass variables from the controller to the view

<?php

class View {
    protected $data = array();

    function __construct() {
        //echo 'this is the view';
    }
    public function assign($variable , $value)
    {
        $this->data[$variable] = $value;
    }

    public function render($name, $noInclude = false)
    {
        extract($this->data);
        if ($noInclude == true) {
            require 'views/' . $name . '.php';    
        }
        else {
            require 'views/header.php';
            require 'views/' . $name . '.php';
            require 'views/footer.php';    
        }
    }


}

in my controller class i used to use like this

class Index extends Controller {

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

    function index() {
        $this->view->assign('title','welcome here codes');
        $this->view->render('index/index',true);
    }

the render function just working fine but there is a problem with the assign function because when i tried to print out the variable from the view it shows nothing

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Code</title>
</head>
<body>
<? echo $title;?> 
some text here
</body>
</html>

i tried to change the protected variable within the View class to public but it didn't effect the problem and i still can't print out any variables from the controller

0

1 Answer 1

1

it shows nothing because you require the view inside the View::render function, so to access your data you should write

<?php echo $this->data['title']; ?>

to avoid this, inside your render function you should create variables from the data array. I mean something like

foreach($this->data as $key => $value) {
  $$key = $value;
}

note: the code above can't live inside your "extract" function because of variables scope.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.