Wednesday, 5 May 2010

Functions, Arguments and Return Values

In this screencast we will make our code more efficient by creating a reusable function to calculate the perimeter of a circle, given its radius.

In programming the main goal is to automate or simplify a task as efficiently as possible. It is often said that lazy people make good programmers since the measure of success is achieving the best output for the least input. "Work smart, not hard" encapsulates this particularly well, provided the quality of the end result doesn't suffer. One way to improve code efficiency is to apply the DRY principle: Don't Repeat Yourself. Functions allow you to do just that.

Functions group blocks of code and allow you to run that code as many times as you like by simply referencing its name as a function call. For example, myFunction(); triggers a function named myFunction. In their simplest form, functions can be compared to ant-hills.
  • The entrance to the ant-hill is like the function call - a deceptively small gateway to a much larger hive full of action.
  • The hive that lies below ground is like the function declaration - the place where the action happens, hidden from view.
  • The ants themselves are like the individual lines of code in the function - individual parts contributing to a common result.
Please note that when you are naming your functions you must avoid terms reserved by the language itself, however those will not be discussed as there are lengthy and comprehensive lists available online.

Variable scope refers to the fact that not all variables are available at all times. Although there are exceptions and ways around this, standard variables are considered local and access to them is restricted, unlike constants which are global by default. For example, a local variable that was defined outside of a function is not accessible from within a function. We can describe this limitation by taking some artistic liberty with the ant-hill analogy. We will imagine that there are several greedy ant colonies with ant-hills in the same area, even though they all eat the same food, they refuse to share with each other and survive on stockpiles in their hive. If functions were truly unable to interact with other parts of your code, they would be much less useful. This is where arguments and return values come into play.

Arguments are used to pass information to a function. To make this adjustment, we must first prepare the function to receive information by adding a variable between the parentheses of the function declaration. For example, function myFunction() { ... } would become function myFunction($myVariable) { ... } note that myVariable is local to myFunction an therefore accessible from within the function. Next we need to specify the information to be passed by adding it between the parentheses of our function call. For example, myFunction(); would become myFunction('example text'); where example text is the string being passed. It is possible to specify more than one argument by using a comma-separate list of variables and values in the function declaration and function call(s), respectively. For example, function myFunction($myVariable, $myOtherVariable) { ... } and myFunction('example text', 'other example text'); would allow $myVariable to receive example text and $myOtherVariable to receive other example text.

Return values are used to get information back from a function, often this is some sort of result such as a calculation, an error, a row from a datasource or a true/false evaluation. For example, function myFunction() { return 3; } would return the integer 3. This means that any time the function runs, the function call that triggered it would take on the return value. For example echo "The number is " . myFunction(); would display The number is 3. Note that PHP halts the execution of a function when it hits a return statement.

The usage of functions will be summarised in the following exercise.

Exercise

Our objective is to calculate and display the perimeter of 3 different circles using PHP. The end result should be similar to what you see on screen now.

We will start by opening the supporting file "circle_properties2.php" which has been set up as a static page. This file is identical to the end file from "circle_properties1.php" which was the previous exercise. First we will wrap the calculations in a function and specify a variable to receive the radius argument, then we will adapt the function to use the radius. Rather than echoing the result directly, we will change the function to return the result. Next we will create a call to the function and pass a value of 3 for the radius argument. Since we removed the echo from the function and had it return a value instead, we will need to echo the function call. Now that we are sure our function is working correctly, all we need to do is copy-paste the function call and pass a different value as the radius. Note that we were still able to use the constant PI inside the function because it is part of the global scope.

If you view your file through a local or live server that can process PHP, you should see the desired result.

Screencast URL: To come

Tuesday, 4 May 2010

Variables and Constants

In this screencast we will compare constants and variables, then use them to calculate the perimeter of a circle.

Constants and variables are both store data and can be used in similar ways, however they serve different purposes and are not interchangeable.

Constants are meant to be used to hold values that will not change during the execution of the script. They are available globally: from inside and outside functions alike. Although it is not necessary, many developers choose to use all uppercase when naming constants so that they are easier to spot. The syntax for defining a constant is: define(name, value); where name is a string representing the name of a constant and value is the data to be stored. For example, you could store a custom value for pi using the code: define("PI", 3.14); where PI is the name and 3.14 is the value. To use the constant you simply reference the name you gave it. For example, echo(PI); would display 3.14. The benefit to using a constant rather than hard-coding the value is simplifying updates and improving stability by reducing possible human error.

Variables hold data that will most likely change during the execution of the script. By default, they are only available locally: from the same function or level where they are declared. The syntax for setting a variable is: $name = value; where name represents the alpha-numeric name of the variable and value is the data to be stored. For example, you could store the radius of a circle using the code $radius = 3; where radius is the name of the variable and 3 is the value. To use the value you simply reference the name you gave it preceded by a $. For example, echo($radius); would display 3.

Their usage will be summarised in the following exercise.

Exercise

Our objective is to calculate and display the perimeter of a circle using PHP. The end result should be similar to what you see on screen now.

We will start by creating an empty PHP file. Next we will define a constant for pi (3.14) and a variable for our radius (3). After that we will use the formula 2πr to calculate the perimeter and store it in a variable. Finally we will echo the perimeter along with an explanatory sentence. Notice that the variable is outside of the quotes and they are concatenated (or joined) by a dot.

If you view your file through a local or live server that can process PHP, you should see the desired result.

Screencast URL: To come

Monday, 3 May 2010

Server-Side Scripting and PHP

In this screencast we will cover the basic concept of server-side scripting and use PHP to create a practical example of how the process works.

A web server works in much the same way as a restaurant - it receives requests, processes them, then sends the result back. It is important to note that the PHP script is not downloaded from the server, only the resulting output is. To go back to the analogy, once you have placed your order, the waiter brings your order to the kitchen at which point the chef prepares your food, the waiter then returns with your food - not the individual ingredients. To put that in terms of a LAMP (or Linux, Apache, MySQL, PHP) server:
  • Linux is represented by the restaurant - the server platform that brings all the parts together
  • Apache is represented by the waiter - the mechanism that receives requests and serves results
  • MySQL is represented by the kitchen's store room - the area where information is held pending use
  • PHP is represented by the chef - the script that processes the request based on logical instructions, pulling information together and preparing the result
It is important to note that this analogy falls short when accounting for how the result is displayed. PHP does not have a native front-end and relies on other web languages for structure and/or style. To use another analogy, the human brain is responsible for controlling the body, however it would fall flat without bones and would be shocking without skin and clothes. The brain, bones and skin represent PHP, HTML and CSS, respectively. This process will be summarised in the following exercise.

Exercise

Our objective is to display a heading that reads "Hello World!" on a web page, as you would using static HTML. The catch, however, is that the text must be output from PHP. The end result should be similar to what you see on screen now.

We will start by opening supporting file "helloworld_start.php" which has been set up as a static page. Since we only want to affect the contents of the h1 tag we can add our opening and closing PHP tags inside of it. For clarity, I'm going to remove the text that was there already. In PHP you need to "echo" things for them appear in the output. Since we want to echo text, also known as a string, we need to wrap it in quotes so that PHP interprets it correctly.

If you view your file through a local or live server that can process PHP, you should see the desired result.

Screencast URL : http://screenr.com/vGC