I am programming in an old fashion – still using functions and not classes. For example, something basic I do when creating a basic template for a site is put the header and footer in a function like so in a file called functions.php
<?php
//header
function outline_start() {
echo '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>my site</title>
</head>
<body>
';
}
//footer
function outline_end() {
echo '
</body></html>
';
}
?>
Then in another file, like index.php I’d do the following:
<?php
include(functions.php);
outline_start();
echo 'hello world';
outline_end();
?>
This can pose issues security wise with needing to use global variables I’ve been told and generally is bad practice – right?
What is the best practice?
Best practices can be best determined by the team you’re working with. The way I see it, you’ve got one of two options:
You can prefix your functions into a sort of “the functions with these prefixes are for these operations”. This is similar to what PHP has been doing for a while, i.e. db_connect() and db_query(). But really, this is very similar to exactly what you already have (outline_start() and outline_end()).
If you want to encapsulate this in a class, you can:
However, most people would recommend you use a view engine approach, or at the very least, a php_include of your header and footer. It is widely accepted that you do your best to keep the HTML out of your PHP code. It makes it easy for CSS, styling, and JS later, if you’re into that sort of stuff. Therefore, if the purpose of your PHP functions is to really just return static HTML, just stick it in another file and don’t worry about trying to PHP5 it up.