As a fairly long member, if not regular member poster, on this forum it has come to my attention that often people do not structure code in such a way as to make it easily readable and maintainable. Te purpose of this topic is to simply give people something to think about. I am not saying that this is the only way to do things but I have found it useful. This is often called templating and some people argue against it but that is for you to decide...
Php and HTML can mix and this can often lead to the following looking PHP code:
Code: Select all
<html>
<head>
<title>Mix</title>
</head>
<body>
<?php
// This function simple outputs different strings
function decide() {
if (!empty($_GET['testvar']) {
echo '<p>This is the test var: '.$_GET['testvar'].'</p>';
} else {
echo "<p>Well you didn't pass in a test var</p>";
}
}
// The $out variable is used to show some output
if (!empty($_GET['myvar']==1) {
?>
<p>hello myvar has a value of one</p>
<?php
} else {
?>
<p>hello myvar does not have a value of one</p>
<?php
}
decide();
?>
</body>
</html>First rule...
1. Have a main PHP block at the top of the file. This should contain all your 'logic' often called business logic.
2. All functions go at the top of the php block.
3. Where necessary set variables for output later.
Compare the previous output with the following...
Code: Select all
<?php
function decide() {
if (!empty($_GET['testvar']) {
echo '<p>This is the test var: '.$_GET['testvar'].'</p>';
} else {
echo "<p>Well you didn't pass in a test var</p>";
}
}
// The $out variable is used to show some output
if (!empty($_GET['myvar']==1) {
$out="<p>hello myvar has a value of one</p>";
} else {
$out="<p>hello myvar does not have a value of one</p>";
}
?>
<html>
<head>
<title>Mix</title>
</head>
<body>
<?php echo $out; ?>
<?php decide(); ?>
</body>
</html>Often you need to use something like sessions or the 'header' command to redirect the user based on parameters passed in, either through a form or directly set via $_GET. Both session_start and headers need to be sent before any output. Even a blank line will throw this. If you have a <?php start on the first line and you do not directly output and output within the php block you are less likely to run into any problems with the error message 'headers already sent'.