It is clear to us that the author's name is repeated throughout the pages, and there emerges an opportunity for further optimization: what if we could define a variable that determines the name of the author ("John Doe"), and simply have different parts of the website to refer to this single variable?
Since header.php
is included in every web page (and happens to less complex than head.php
), we can opt to define a new variable here:
header.php
<?
$name = "John Doe";
?>
<div id="header">
<h1>John Doe</h1>
</div>
The new $name
variable is now available for the remainder of each web page:
We can now use PHP code to replace all HTML instances of "John Doe" with references to the above variable:
header.php
...
<div id="header">
<h1><? echo $name ?></h1>
</div>
index.php
...
<div id="content">
<img src="http://i.pravatar.cc/500?img=1">
<h2>Toronto, ON</h2>
<p><?= $name ?> is a Toronto-based designer.</p>
</div>
...
<?= $name ?>
is a shorthand form of <? echo $name ?>
, and performs the same way.
footer.php
...
<div id="footer">
Made by <?= $name ?>
</div>
Upon returning to header.php
and updating the original $name
variable, we can now confirm that all references to the variable are also affected: