BloggerAds廣告

相關文章

2015年6月26日 星期五

php pass data to include_once() require_once()

The following code shows how to pass params to included files in php
it works also in the following functions:
include()
include_once()
require()
require_once()


application.php
Using an Associative array to carry variables would be an ideal option.
<?php
$m = new Main();

$items = array(
 'name'=> 'John Doe',
 'items'=>array('stone', 'knife', 'card', 'etc...')
);

$m->loadViewWithParams('item_list_view.php', $items);
?>

Main.php
For variables which visibles to the line above the include(), they also visibles to the included file.
We simply create variables just above the include() just the way that many people do so.
Since we've passed an associative array to loadViewWithParams(), we will break the array into variables in runtime.
<?php
class Main {
/**
*
*@param $path string the file path to load.
*@param $params array an associative array which carry data to the loaded file.
*/
  public function loadViewWithParams($path, $params = array()){
    //we use a foreach to parse the array to variables
    foreach ($params as $key => $value ) {
      $$key = $value;
    }

    include_once($path);
  }
}
?>

item_list_view.php
consider the application.php above
the loadViewWithParams() method converted the array into variables
now both $name and $item were passed to the included file
<div>
 <h1>Welcome, <?php echo $name; ?> </h1>
 here are your items
 <ul>
  <?php foreach($myItemList as $item): ?>
  <li><?php echo $item; ?></li>
  <?php endforeach; ?>
 <ul>
</div>

沒有留言 :

張貼留言