PHP is an object-oriented language, based (loosly) upon C++. It has classes, methods, member variables, and all that other good stuff. It runs on your web server, not in the client, but the HTML, JavaScript, and other stuff such as CSS blocks that it emits with its output commands are run on the client.
The purpose of this tutorial is to explain why you don't want to mix your PHP and HTML, JavaScript, etc. One reason is if you do that, it becomes pretty much impossible to debug. Another is that is it inefficient.
- Use classes and methods to build up your output HTML strings from the logic, passed $_GET, $_POST, and other global variables, and ONLY output them once they are completely formed.
- This allows you to recursively call (include) the same PHP code from forms that are created and output, providing you the capability to get some really complex stuff working that would be impossible otherwise.
- You can better validate passed variables, SQL query predicates, etc.
- If needed, you can emit debug data when inside your class member functions that would not be visible if you tried to do that when inside a JavaScript block of code.
So, don't mix PHP and HTML, etc. Build your output strings inside your PHP class functions and only output them once you have finished.
Example (mostly pseudo code):
<?php
class MyClass {
public
$output = '';
$debug = false;
function __construct() {}
function __destruct() {}
function display()
{
echo "$output";
}
function addToOutput($aString)
{
if ($debug === true)
{
// Escape tags in $aString so it won't be interpreted as HTML commands
// by the client - just as text.
$massagedText = stringify($aString);
echo "MyClass::addToOutput - $massagedText<br/>";
}
$output .= $aString;
}
}
MyClass mc = new MyClass;
mc->addToOutput('Some HTML code here to append to $output.');
mc->display();
?>
Inside the constructor, you can evaluate the $_GET, $_POST, and other variables (or arguments if you wish) to begin building the output string which can be as complex as you wish. This methodology also allows you to add forms, tables, CSS blocks, JavaScript and such as needed, simply by calling mc->addToOutput($someString). When the mc->display() method is called, all that stuff is sent to the client as a single message, and executed/displayed there as appropriate. Because there is only one message from server to client, it is much more efficient (faster) than many small messages.
So, this allows you to use the server for what it was designed for - to serve data to the client, and allows the client to do what it was designed for - to display data and take user input to send back to the server for further processing.