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?).
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 .
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.
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.
extract
works with an associative array.
$this->view('profile',
[
'profiledetails' => $profiledetails,
'profilestatus' => $profilestatus
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With