Ajoy2w Ajoy2w - 1 month ago 4x
PHP Question

Why is my conditional statement not working?

I'm trying to use one header.php to process both my public pages and my admin pages using conditional statements. I can get this technique to work when I use an include, but I learned a different technique for including files using a function and now my conditional statements for admin and public are not working.

So this code is at the top of my header.php wrapped in php tag.

if (!isset($layout_context)) {
$layout_context = "public";

Then in my header tag I have sections of code like this

<?php if($layout_context == "public") { ?>
<header id="home">
<?php ; } elseif($layout_context == "admin") { ?>
<header id="cms-pages">
<?php ; } ?>

Then in all my pages I put this code at the top

<?php $layout_context = "public"; ?>


<?php $layout_context = "admin"; ?>

When I use this code:

<?php include("includes/layouts/header.php"); ?>

I can get those conditional public and admin codes to work, but when I try and use this technique to include my header.php

<?php include_layout_template('header-admin.php'); ?>

function lives in the functions.php in the includes folder.

function include_layout_template($template="") {

I can't get the conditional code to work. Does anyone know why that might be?

Thank you :)


You state that after a standard include include("includes/layouts/header.php");, you are able to use $layout_context, but that after an include using a function include_layout_template('header-admin.php');, you are not.

This is to problems with variable scoping.

Your $layout_context is defined within the header.php file, outside of any function declaration.

In a file like this, if you include it at the global level, then the variables in it will be come global variables.

However, if you include it from within a function, then those variables become variables within that function.

Thus when you call include_layout_template(), the variables are created, but are only scoped within include_layout_template(). As soon as the function returns, those variables are no longer available.

The quick and dirty solution here is to define them as global within the header.php file. So add global $layout_context; to the top of the code in this file, and the same for any other variables declared within it.

That will probably get you up and running with the minimal work from where you are now.

However, global variables are a very blunt tool and generally considered very poor practice for a number of reasons. You would be much better off rewriting your config variables so that you can reference them from a function call or object. This way you can include them from wherever, any they will still be accessible in the same way.