PHP using extract () to pass array values ​​as variables and display it on the page

I am trying to create a function view($path,$data)

in php

, the main functionality includes a specific file from a directory and pass data / variable to this page, I managed to create $path

and was able to include the definition path, now my next step is to pass the values $data

to my included page and want to convert each array label into a variable.

My php class is below classes.php

.

define("SITE_NAME", "process");

 class helpers {


        public function view($path, $data) 
        {

            $dir = $_SERVER['DOCUMENT_ROOT'].SITE_NAME."/";

            include($dir.$path.".php");

            return extract($data);



        }  

}

      

On my index.php

require_once('classes.php');

$helper = new Helpers();

$data['title'] = "My Test";
$data['test'] = "test1";

$helper->view('test',$data);

      

So now on my test.php I go to echo $title

which, believing it will return a value My Test

, to check if I get values ​​from index.php

I was able to output $data

withprint_r

Array ( [title] => My Test [test] => test1 )

Any advice how can I achieve? i tried to use the function extract()

but don't know if the syntax is correct. Thanks in advance!

+3


source to share


1 answer


Because the refund is limited to only one value.

By extracting it, you are taking one value the array

and splitting it into many.

Personally, I avoid using things like extract

and in my code $$var

as it destroys my IDE and makes reading nearly impossible. However, it makes sense to use it in this case, since it is limited in scope, which limits the possibility of accidentally overriding another variable inadvertently.

http://php.net/manual/en/functions.returning-values.php

The function cannot return multiple values , but similar results can be obtained by returning an array.

and

http://php.net/manual/en/function.extract.php

extract - import variables into the current symbol table from an array

symbol table ~ area

Further

Return Values: Returns the number of successfully imported variables into the symbol table

public function view($path, $data)
{

    $dir = $_SERVER['DOCUMENT_ROOT'].SITE_NAME."/";

    include($dir.$path.".php");
    return extract($data); //returns the variables successfully imported from $data
}

      

...

As you can see, as soon as you call return, this terminates the execution of the current function and closes that area. You will have to reorder them, so the variable is assigned first.

I'm guessing the included file in the method is like this, it wasn't in the OP.



    <h1><?= $title; ?></h1>

      

Technically, you have nothing to return because the HTML will naturally be caught by the output buffer and displayed when the script finishes executing. However, this is not very clean. The correct way is to take control of the output buffer like this:

    public function view($path, $data) 
    {
        $dir = $_SERVER['DOCUMENT_ROOT'].SITE_NAME."/";

        extract($data); //variables must exist before importing where they are used.
        ob_start();
        include($dir.$path.".php"); //capture this output
        $view = ob_get_clean();
       return $view;
    }  

   $out = $helper->view('test',$data); //out now contains the HTML output from the included file.

      

Then you can echo

go out. IMO this is better because you can insert this HTML output into another dataset and pipe it to another template. Which is useful for things like a reusable header or footer or navigation bar, etc.

Consider this

$head['page_title'] = "My Test";
$body['head'] = $helper->view('header',$head); //create head and assign to body

$body['name'] = 'John Smith';
echo $helper->view('body',$body); //create body (with head inserted) and echo

      

And header.php

<title><?= $page_title; ?></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

      

And body.php

<!DOCTYPE html>
<html>
    <head>
        <?= $head; ?>
    </head> 
    <body>
       <p><?= $name; ?></p>
    </body> 
 </html>

      

The result will now be something like this

<!DOCTYPE html>
<html>
   <head>
      <title>My Test</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  </head>   
  <body>
     <p>John Smith</p>
  </body>   
</html>

      

Now both pages are merged into one, which is displayed. You could take this to whatever level of reuse you wanted, but it would save you typing and make it easier to view.

But as I said, you can just let it naturally infer

    public function view($path, $data) 
    {
        $dir = $_SERVER['DOCUMENT_ROOT'].SITE_NAME."/";

        extract($data); //variables must exist before importing where they are used.
        include($dir.$path.".php"); //capture this output
    } 
    //outputs when script is done.

      

+4


source







All Articles