Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting contents with extract($variables), but the variables are undefined

I haven't gotten the hang of the extract() function, and transferring variables. I have a method in a user controller where some variables are defined, and sent in an array to a view function in a parent controller, where the array is extracted. Then the view is required. But the variables turn out undefined. The array contents can be printed though.

Here is the user controller with a simplified profile function:

class User extends Controller{

    public function profile(){

         $profiledetails = $this->profiledetails();           
         $profilestatus = $this->profileStatus();            

         $this->view('profile', [$profiledetails, $profilestatus]);
}}    

The variables are sent to the view function in parent Controller:

class Controller {
    public function view($view, $variables =[]){                    

    extract($variables);

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

And in the view, 'profile.php', the undefined variable error is shown. I thought that the "extract()" function would make $profiledetails and $profilestatus available as variables in the view. What am I doing wrong? Maybe I'm using the wrong type of array, or I should use "variabe variables" or something.. (in that case, how?).

like image 558
Galivan Avatar asked May 30 '15 23:05

Galivan


People also ask

Why are my variables undefined?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Why is my variable undefined PHP?

Undefined variable: the variable's definition is not found in the project files, configured include paths, or among the PHP predefined variables. Variable might have not been defined: there are one or more paths to reach the line with the variable usage without defining it.

Why is my array undefined?

You get undefined when you try to access the array value at index 0, but it's not that the value undefined is stored at index 0, it's that the default behavior in JavaScript is to return undefined if you try to access the value of an object for a key that does not exist.


1 Answers

extract works with an associative array.

    $this->view('profile', 
      [
        'profiledetails' => $profiledetails, 
        'profilestatus' => $profilestatus
      ]);   
like image 64
Ali Gajani Avatar answered Sep 28 '22 01:09

Ali Gajani