This is more of a 'How should I?' rather than 'How do I?' question.
Generally, what is considered the best way to pass variables to an included file?
For example, let's say I'm using a fragment for a menu, and want one of the menu items (the current one) to have a certain class name (this is a very generic sample - not something I'm actually using):
<?php
$links = array(
array('text' => 'home', 'href' => 'home.php'),
array('text' => 'about', 'href' => 'about.php'),
array('text' => 'contact', 'href' => 'contact.php')
);
?>
<ul>
<?php for($i = 0; $i < 3; $i++) :
$link = $links[$i];
$is_active = ($i == $active_index);
?>
<li><a <?=($is_active ? 'class="active"' : '')?> href="<?=$link['href']?>"><?=$link['text']?></a></li>
<?php endfor; ?>
</ul>
i'll call the above 'menu.inc.php'. obviously it's looking for a variable (int) called $active_index
to determine which link to give the '.active' class to.
so - you could just define $active_index
before calling the include, but this seems like poor practice to me since perhaps a variable of that name might have been defined for something else earlier and a later part of the script is still looking for it.
or - you could use an absolute path and append variables using a querystring (include 'menu.inc.php?active_index=1'
), but again that seems like a bad idea since you might need the 'real' $_GET
within any given include
.
or - you could start each included file with ob_start
and return ob_end_clean()
, then use something like this to get the return:
function load_view($file, $variables){
extract($variables);
return include($file);
}
// passed like
<?=load_view('menu.inc.php', array('active_index' => 2))?>
but again this seems to have a number of cons (having to restructure all your include files accordingly with the ob
functions and a return
statement).
I like an object for this, as described in this MVC stack post. In a file called viewMenu.class.php,
class viewMenu
{
private $active_link;
public function __construct ( $active_link )
{
$this->active_link = $active_link;
}
//If the constructor doesn't work for you, try a "set" method.
public function view ()
{
$active_link = $this->active_link;
include_once ( "menu.inc.php" );
}
}
Defining $active_link inside the view method contains the variable scope of $active_link to within the method. Then call this code:
$aViewMenu = new viewMenu( $active_link );
$aViewMenu->view();
However, I'm nearly new to MVC in PHP, and I welcome reproach.
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