-1

i am trying to build an Model/View/Controller framework, i want to include my view file.
i copied the code from codeigniter, then i edited it:

if( ! is_file($file_location)){
    throw new Exception("`$name` is Not Found in Views");
}
$output = (function (): string {
    // extract($data);
    ob_start();
    include $file_location;
    return ob_get_clean() ?: '';
})();// this is line 25

and i get an exception and i caught it:

Error:Path cannot be empty
line        25  
function        {closure}
  • 1
    I assume this is due to `$file_location` not being defined in the scope of the callback. Did you forget to `use` it? – El_Vanja May 17 '21 at 08:25
  • i edited my question to add what did i check, also i did echo the location, it is `(C:\xampp\htdocs\pulse\app\Views\user.php)` – mohamad zbib May 17 '21 at 08:26
  • Checking outside of the callback doesn't change anything, as that variable still doesn't exist within your anonymous function. Also, in the `if` you use `$file_loc`, while inside the callback it's `$file_location`. – El_Vanja May 17 '21 at 08:27
  • Does this answer your question? [Callback function using variables calculated outside of it](https://stackoverflow.com/questions/4588714/callback-function-using-variables-calculated-outside-of-it) – El_Vanja May 17 '21 at 08:28

1 Answers1

1

Maybe this should work:

if( ! is_file($file_loc)){
    throw new Exception("`$name` is Not Found in Views");
}
$output = (function () use ($file_loc): string {
    // extract($data);
    ob_start();
    include $file_loc;
    return ob_get_clean() ?: '';
})();// this is line 25
u-nik
  • 488
  • 4
  • 12
  • We generally look to avoid duplicated content. The explanation how to use outside variables in a closure already exist on the site and the question should rather be flagged as a duplicate. – El_Vanja May 17 '21 at 08:37