How to structure a basic PHP file

When creating code, PHP gives us a huge freedom. Since PHP is compiled at runtime, it can be mixed with any text inside the file. Then, when the code is compiled, the content of the file gets to the output (usually your browser).

If you create a small project, using this technique is totally ok. The problem starts when the project starts to grow.

This article is about a small sized project with very few PHP files. In any case, readability is a very important thing. You know the case when you get back to your code after a long time to edit something, and you just are lost. To make the code readable and logically sound, there is a structure that can be used to achieve it.

If the PHP file contains HTML in it, usually it is good to separate the two. The file starts with PHP, containing all the logic needed. All the data that needs to be printed on the screen is added into variables. These variables are then used in the HTML. This clearly separates the logic from the actual data output. So the structure looks something like:

In the PHP section, where the logic is, you can also separate the logic that handles POST requests for example. It is good practice to create variables that will control such events and that hold information about these events. These variables than can control the HTML part accordingly. For example:

This makes your code clear and if needed, later you can separate the logic from the actual html. Using such a structure is beneficial for you. Since PHP is a very loose language, you are the one that needs to pay attention to such things, but you will not regret it.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">