May 14, 2012
Using a variable inside an included file from function
Question by Djave
I’d like to have a header.php file throughout my site. I currently have the following:
header.php
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="<?php if(isset($depth)){echo $depth;};?>css/style.css">
functions.php
function include_layout_template($template="", $depth="")
{
global $depth;
include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
index.php
<?php include_layout_template('header.php', "../"); ?>
But $depth dissappears, I can’t even echo $depth; its just blank. How can I get the depth variable for use in header.php?
Answer by Sergey
You have to rename depth variable in function call
function include_layout_template($template="", $my_depth="")
{
global $depth;
//if need $depth = $mydepth
Answer by Starx
Your $depth
variable is disappearing, because it is passed as parameter first but then defined to use the global parameter.
I will explain with an example:
$global = "../../"; //the variable outside
function include_layout_template($template="", $depth="")
{
global $depth; //This will NEVER be the parameter passed to the function
include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
include_layout_template("header.php", "../");
To solve, simply modify the function parameter other than the depth itself.
function include_layout_template($template="", $cDepth="") { }