-1

I am creating a fixed header for all my website's pages.

I want to include a page title in each index.php which is part of the page's header, coded in an included header.php, The page title should be declared on the page itself and then referenced in the static header.php file for css and such.

My current method looks something like this between two files (index.php and header.php):

index.php:

<html>
<title>Site Title</title>
<?php
    $pageTitle="About";
?>
<link rel="stylesheet" href="style.css">
<?php include_once("header.php"); ?>
<body> ...

header.php:

<div id="pageTitle">
    <?php function getText() {echo $pageTitle;}
        getText();
    ?>
</div>

How should the files be modified to pass the pageTitle variable into the included header.php file?

T H Wright
  • 77
  • 1
  • 9
  • Your whole model is just plain wrong! I think you might want to look at a templating engine like Smarty to do this correctly. If you don't use a templating engine then you should try and keep the PHP out of your HTML as much as possible - so put PHP at the top of the file and then HTML below it (or in an include file) where all you have in the HTML is items like – Paul Coldrey Aug 12 '15 at 02:35
  • 1
    It would be helpful to you to read up on php variable scope - http://php.net/manual/en/language.variables.scope.php This would address your issue with your `$ pageTitle` inside your function – Sean Aug 12 '15 at 02:37
  • Thanks for the blunt advice. I will get to researching! – T H Wright Aug 12 '15 at 02:37

1 Answers1

0

If you remove the function definition and call so your code is just the echo statement, it should work. So, your header.php code would be:

<div id="pageTitle">
    <?php echo $pageTitle;
    ?>
</div>

This is because of how variable scope works in PHP. Variables created and/or referenced inside a function are considered local variables, unless they are explicitly marked as global using global $variableName. See: http://php.net/manual/en/language.variables.scope.php

Alternatively, as a more transparent way of passing the variable, you could wrap all of your header code in a function and call that function from index.php. That would look like: index.php:

<html>
<title>Site Title</title>
<?php
    $pageTitle="About";
?>
<link rel="stylesheet" href="style.css">
<?php 
include_once("header.php");
displayHeader($pageTitle); 
?>
<body> ...

header.php:

<?php function displayHeader($pageTitle) { ?>
<div id="pageTitle">
    <?php echo $pageTitle; ?>
</div>
<?php } ?>
BurningLights
  • 2,387
  • 1
  • 15
  • 22