I have worked in PHP before, but mainly some small touches that actually concern the output HTML. I am more of a front-end guy. Now, I am building a small-scale website that has a lot of duplication in the head, header, and footer but differs a bit in content (almost your typical "template" style design). I am not sure how I should handle dependencies in such scenario. I have variables, I have functions, and I have includes and requires. But where goes what?
For instance. I have a config.php
file that contains a couple of global static variables that are often used (such as $home
which is the base url - this is necessary for testing locally in subdirectories). I require this config file at the top of each other PHP file. I think that should be sort of alright?
But then: what to do with global variables that change per page. Simple example: Let's say I have this code in page.php
:
<?php include "header.php"; ?>
and header.php looks like this:
<header>
<h1><?php echo $pageTitle; ?></h1>
</header>
Is it simply as easy to put the value for that page in page.php
? Like so:
$pageTitle = "I like bananas";
<?php include "header.php"; ?>
This concerns me, because if you have a lot of these things - PHP turns ugly: after a while your base PHP file (page.php
) is cluttered with variables. Not thousands of them, obviously, but I guess it could be around a dozen for my project. Is that a "problem" or is that something that usually happens? If it's not usual, how then should I handle variables in PHP?
And what about functions? For instance, if I want to add a class to a certain item in header.php
, if a variable is 5
(obviously the real example is more elaborate), I could write a function like so:
function checkBananaAmount($int) {
if ($int == 5) echo 'class="eat-bananas"';
}
and call it like so:
<div <?php checkBananaAmount($myBanana); ?>></div>
The question is, would I put this function in a separate file (similar to Wordpress' functions.php
, or would I just place it in header.php
? If the former, does that mean I have to require "functions.php"
in each page with one of these functions as well?
As you can see I am wondering how the basic structure of PHP projects are: how to sort variables and functions, how to keep things neatly organised and so on, without losing productivity and keeping efficiency.