The first step – part two

Introduction

Last time in part one (https://www.elearningworld.org/the-first-step-part-one/) we setup a web server and looked at PHP output. This time in part two we will look at:

  1. variables
  2. functions
  3. scope and globals

If you’ve not read part one, then please do so before this part so that it will make sense.

Disclaimers

Firefox® is a registered trademark of the Mozilla Foundation – www.mozilla.org/en-US/foundation/trademarks/policy.

Ubuntu® is a registered trademark of Canonical Ltd – ubuntu.com/legal/intellectual-property-policy.

“Raspberry Pi” is a trademark of the Raspberry Pi Foundation – www.raspberrypi.org/trademark-rules.

Apache and Apache HTTP Server are trademarks of The Apache Software Foundation – www.apache.org.

Other names / logos can be trademarks of their respective owners. Please review their website for details.

I am independent from the organisations listed above and am in no way writing for or endorsed by them.

All example ‘code’ presented is written by myself, please feel free to copy for educational purposes only.

A reminder if it does not work

If something goes wrong, then you need to look in the error log file. On the Pi, this will be located in the ‘/var/log/apache2’ folder as ‘error.log’ and you can use the command ‘tail’ to see the most recent events as the file is appended to. In other systems, hunt around for ‘error.log’.

Variables

Think of a variable as a dynamically sized box. It is a container to hold what you want to store in it. Over time its contents can change, become bigger or smaller. An example would be ‘age’ of a person. For a given individual this will be set and then increase over time. Or it could be the list of participants who have signed up for a course where over time, some can be added and some drop out.

Variables have a type depending on what you want to store. This is so that the computer knows how to manage the variable on the available hardware. Thus translate the ‘data’ you store in a variable in to ‘bits’ (en.wikipedia.org/wiki/Bit).

Some variable types (such as an ‘array’ (en.wikipedia.org/wiki/Array_data_structure)) are containers for lots of other variables. PHP’s types are listed here: www.php.net/manual/en/language.types.php.

PHP is a loosely typed language (en.wikipedia.org/wiki/Strong_and_weak_typing), this means that the type of a variable is not known until a value is assigned to it. It can also change type as the program runs, en.wikipedia.org/wiki/Type_conversion. Other languages have ‘strong typing’ which means that the type of the variable must be defined before it is used.

As we did in the last part, in the folder ‘mycode’, use ‘nano’ to create the file ‘vars.php’:

Note: PHP can use both ‘’ and “” as string containers. When the former, any variable syntax is not evaluated to show the variable value and with the latter it is. So if $one is 42, then ‘$one’ will show $one and “$one” will show 42.

Use a URL like ‘http://192.168.0.2/mycode/vars.php’ in a web browser to see the result:

So we can see how PHP is:

  • Able to tell the type of a variable from its first assignment.
  • Increment it sensibly, so with the ‘a’ character it becomes a ‘b’ and ‘1’ becomes ‘2’.
  • Change the type of a variable depending on its contents. So ‘$two’ has changed from a string to an integer.

We can also see one form of how loops are orchestrated with ‘for’ here – www.php.net/manual/en/control-structures.for.php. And this in general terms is perhaps the hardest thing about learning how to program, understanding one thing often depends on another and that another. This can be a ‘circle’ of dependency whereby you have to loop around gradually understanding each item before the whole makes sense. You do have to persevere and not give up!

Functions

In solving a problem where a computer is a part of the solution in terms of software, that problem will be broken down into many solutions that form the whole solution. Often a solution can depend on many other solutions and those solutions used more than once. It is like working in a multi-floor building performing many different tasks, you’ll use the stairs more than once. Software allows you to break down the solution into many smaller solutions, one form is a ‘function’ (we will cover classes and methods next time).

A ‘function’ can be used many times to do the same thing and can have ‘parameters’ as an input and thus produce a different result. Just like asking somebody for the time of day, same function different result depending on what time it is. Or asking about the time table for a bus, same function, but a different result if its bus number ‘42’ or ‘64’.

In our example we will create a function that lets you know when your meeting will be from now. It takes two parameters, the hour and minute of the meeting and then combines that with asking the computer for the current time. If you want to find out how your computer keeps its time updated then read about the ‘Network Time Protocol’ (en.wikipedia.org/wiki/Network_Time_Protocol), the ‘internet’ is more than just web pages!

In the folder ‘mycode’, use ‘nano’ to create the file ‘func.php’:

Use a URL like ‘http://192.168.0.2/mycode/func.php’ in a web browser to see the result:

We can see how:

  • The function is defined with the ‘function’ keyword with its name afterwards. This does need to be unique within the current scope (more on ‘Scope’ later).
  • There are parameters of ‘$hour’, ‘$min’ and ‘$now’ that are in the same syntax as we learned about in ‘Variables’.
  • Further down there is a call to another function ‘getdate()’ with no parameters to get the current date and time, which we store in ‘$now’. This we pass to our function ‘meetingAt’ as a parameter, it contains an array containing the different elements, like the current day, and critically array index ‘0’ contains a number which is the number of seconds since the 1st January 1970 – Unix or ‘epoch’ timestamp (en.wikipedia.org/wiki/Unix_time). It is built into PHP (www.php.net/manual/en/function.getdate.php) so we don’t need to create it ourselves.
  • Then the ‘mktime’ PHP function (www.php.net/manual/en/function.mktime.php) is used to create a date/time for our meeting on the current day. Where we know the hour and minute of the meeting, but not the rest. It returns the epoch timestamp for the meeting time.
  • Because we now have two epoch times that are just number of seconds, then we can perform a calculation to work out the difference between the two and then output that.
  • Then we define our meeting times and because arrays have ‘indexes’ that can be strings, I’ve defined ‘h’ and ‘m’ to represent the hour and minute of the meeting. As each meeting has two values for the hour and minute, this is stored as an array. Thus we can have an array storing many arrays.
  • Then we have our actual output where we ‘loop’ over the ‘$meetings’ array with the ‘foreach’ keyword (www.php.net/manual/en/control-structures.foreach.php). This allows us to iterate over each item in our array that happens to be an array with the hour and minute to pass to our ‘meetingAt’ function. And so because there are three items, then ‘meetingAt’ will be called three times.

Scope and Globals

The word ‘scope’ is perhaps is one of the most critical concepts to understand about software. It defines at any point what your ‘code’ can ‘see’. By ‘see’ this means ‘has access to’ and ‘access’ can be to ‘functions’, ‘variables’, ‘classes’ and ‘methods’. By ‘access’ this can be interpreted as ‘able to use’ but it does not mean ‘modify’ as you might be able to access a variable but not actually change it.

In PHP and other languages, scope is ring-fenced by the curly brackets ‘{}’. They are the dividers between one scope and another. A scope can contain one or more scopes, just like a ‘Matryoshka doll’ (en.wikipedia.org/wiki/Matryoshka_doll). In PHP anything outside the uppermost brackets (top level scope) is in the ‘global scope’ and to access something like a variable in the global scope from within another scope then you need to use the ‘global’ keyword.

In the folder ‘mycode’, use ‘nano’ to create the file ‘scope.php’:

Use a URL like ‘http://192.168.0.2/mycode/scope.php’ in a web browser to see the result:

We can see that:

  • We’ve used a HTML ‘table’ to format the output.
  • The number after the hyphen represents the index of access to test that variable.
  • After the colon, the value of the variable at that time or blank if it cannot be accessed – it is not in scope. Look in the ‘error.log’ for ‘Undefined variable’ messages.
  • The ‘globalscopevar’ can be seen in the global scope and once the ‘global’ keyword has been used, the function and its loop.
  • The ‘functionvar’ can only be seen in the function and its loop.
  • The ‘loopvar’ can be seen both in the loop and surprisingly, the function too, even though its only defined within the loop. So not all scopes are completely the same.

Further reading

To learn more about PHP, you could choose to visit:

Conclusion

In this post we have learnt about:

  1. Variables.
  2. Functions.
  3. Scope and Globals.
  4. Reminded of where to look for error reports.

I hope you’ve progressed with your learning of PHP, next time we will continue on our journey.

Gareth Barnard
Latest posts by Gareth Barnard (see all)
blank

Gareth Barnard

Gareth is a developer of numerous Moodle Themes including Essential (the most popular Moodle Theme ever), Shoelace, and other modules such as course formats.

2 thoughts on “The first step – part two

Add a reply or comment...