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="") { }

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!