Mike Abineri
Mike Abineri

Reputation: 399

Converting array key and values into single variables

I know that you can use extract() to achieve this however my circumstances are as followed:

I am building a very small basic MVC framework for personal projects and I have this in my controller:

 public function index(){

    $data = [
      'title' => 'Welcome'
    ];

    $this->view('pages/index', $data);
 }

As you can see this passes the data array into the view and you can echo it like:

echo $data['title'];

But I want to echo it like echo $title; I know that extract() can do this but that means I have to manually put extract($data); at the top of every page which isnt the end of the world but I was just curious if there was a way it could be done automatically? I have tried to use extract by putting it inside the view function but that did not work. I have also tried to use extract by putting it in the header file that is required_once in index.php (thus making the header file a static header thats always required) but neither has worked so any advice would be great.

Here is the code for the view function as requested:

public function view($view, $data = []){

      if(file_exists('../../views/'.$view.'.php')){

        require_once '../../views/'.$view.'.php';

      } else {

        die('View does not exist');
      }
    }

Upvotes: 0

Views: 63

Answers (2)

Mike Abineri
Mike Abineri

Reputation: 399

Here is where I went wrong, I put extract in the view method before and it didn't work.

However the advice here was to put it in the view function and I now understand that I put the extract function after require_once '../../views/'.$view.'.php'; I just put extract before that line of code and it is now working!

Upvotes: 0

Simple that is it ,use compact and extract function

index method



 public function index(){


      $title='Welcome';


    $this->view('pages/index', compact('title'));
 }


Wiew method


public function view($view, $data = []){

      extract($data);

      if(file_exists('../../views/'.$view.'.php')){

        require_once '../../views/'.$view.'.php';

      } else {

        die('View does not exist');
      }
    }

In html


<h1> hello <?php echo $title; ?></h1>

Upvotes: 1

Related Questions