This week I continued learning how to work with PHP. Among the material for this week were functions and strings, which for building a website are very important. On my Sandbox Website I wrote a PHP script that uses functions. You can find the page for it here, or follow the link at the bottom of this post.
For this page, I built it around a function that simply prints a given string 3 times. I included this in a separate PHP file because I wanted to make the function reusable if I wanted to use it again later. You can see the code for it below:
<?php
//Small script to define functions used on the Module7.php page
//Repeats a string three times
function repeatThrice($message) {
echo $message . "<br>";
echo $message . "<br>";
echo $message . "<br>";
}
?>
Code language: PHP (php)
Then I built the actual page as a PHP script, which becomes a simple HTML document when it is sent to the client. Thus the client cannot see what the PHP is, the only see the result of the script.
This brings me to an interesting point about PHP, is really a language built around the idea handling text data or strings. Because an HTML page is simply a document, data can only really be displayed with strings. This is where functions and strings become connected. To build maintainable, readable code, it is necessary to make code more abstract. This means building objects and functions that can be used anywhere. And while functions can do all kinds of complicated algorithms and play with data, at some point a result will have to be passed on to the client. That result will have to be a string because the PHP compiler will write in new HTML code. For example, in the script above I included HTML break line tags so that the result is easier to read. Had I chosen to do some computation with numeric variables, in the end the echo
statement would convert the result to a string.
Links:
Module 7 Sandbox Page: http://simon-liles.epizy.com/Module7.php