Week 3

Updated on 28 Dec 2018

Structured Programming

Providing structure to your code is important for maintainability, readability, file size and efficiency. One technique of ‘structuring’ your code is to use procedures / functions / methods / sub-routines.

Some languages differentiate between procedures and functions, and yet some don’t refer to functions or procedures but rather ‘methods’. Some languages even go further by having ‘sub-routines’.

At the heart of all of these is their common goal. Encapsulation of common code within a function so that it can be reused again and again.

Questions:

  • Do you know what programming tools / languages refer to methods, functions, procedures or sub-routines?
  • How are events or triggers different?
  • Do you know what properties or attributes are, and how do they differ from procedures?
  • How do you name your procedures?

Functions

PHP provides the ability to write and call your own user-defined functions. As with most modern programming languages, PHP provides plenty of flexibility when you define your functions. Ability to pass parameters, return results, provide default arguments as well as pass by reference are some of the features PHP offer you when defining your own functions.

Using and defining functions is an important step in the concept of modular design. This is because common code that is used throughout your program can be written once, and accessed many times. In some cases the code / functions can be written as part of a ‘library’ and accessed by many different applications.

Questions:

  • What is a library?
  • What is meant by default arguments and return results?
  • How does pass by reference differ from pass by value?
  • How much code can a function contain?

Using Functions

When learning a new language, it is always good to start with the part of the language you can relate to before moving onto more language or tool specific features. We started off with the basics; variables, loops and arrays etc… Lexical structures that we could relate to with other programming languages (if we knew them).

When it’s time to look at the built-in functions, one of the best areas to look into (and compare) is strings. Strings can be defined as a variable containing an indeterminate number sequential characters or numbers. Most programming languages have string variables and functionality to some extent.

The most common of functionality available for strings (in most languages) is the ability to count the number of characters, extract a sub-string, find the position of a character, reverse the sequence and insert a character into the string. Most modern programming languages also provide operators to act on strings as well, and very advanced programming languages allow you to define your own operators.

Here are some common string functions found in PHP.

  • strtolower
  • trim
  • substr
  • strlen
  • strpos
  • strrev

Here are some Web specific string functions found in PHP.

  • get_meta_tags
  • nl2br

Examples:

$Unit = "COMP306 Software Design and Development";
echo strlen($Unit);

$UnitCode = substr($Unit, 0, 7);

echo substr($Unit, 8, strlen($Unit)  8);
echo substr($Unit, -4, 4);

Questions:

  • What is the expected output from the example code?
  • What do the string functions do?
  • Is there an opposite function for strtolower?

Defining Functions

Defining and calling your own functions in PHP is very easy. Here is an example.

function WordCap($text)
{
$words = explode($text, ' ');
for($i = 0; $i < sizeof($words); $i++)
  $words[$i] = ucfirst($words[$i])

$value = implode(' ', $words);
return $value;
}

Here is an example of how to use the function, WordCap.

$message = "I must learn more about strings and arrays";
echo WordCap($message);

This could have also been written like this:

echo WordCap('I must learn more');

Or like this:

$message = WordCap('I must learn more');

Questions:

  • What does the WordCap function do?
  • Examining the Code, what do you think implode and explode do?
  • What would be the output from the echo statements?
  • Are there any other ways to use the functions?

The WordCap function returns a value from the function. You don’t have to return a value from your user-defined functions, nor do you have to assign variables to the returned values!

The WordCap function is a pretty useful function to have around, however PHP will complain if we try to call the function without passing it any parameters.

Warning: Missing argument 1 for WordCap() in d:\my documents\My Site\php\Examples\ereg_test.php on line 12

The PHP script will continue to run with a warning, however an error will halt the continued execution of the PHP script.

Default Arguments:

Default Arguments allow us to define functions with the function parameters being optional. That is, we could redefine the WordCap function so that it worked regardless of whether an argument was used when we called the function.

function WordCap($text = 'hi')

If we called the WordCap function with no arguments, then the WordCap function will ‘pretend’ you sent it ‘hi’.

Most of the PHP functions that you use and define will have arguments that are passed by value. However it is also possible to define functions that have parameters that are passed by reference.

Questions:

  • Do you remember what pass by reference means?
  • How do you define a function with parameters that are passed by reference?
  • Why would you use pass by reference?

External Files

The use of external files will be very important as you develop your PHP scripts. When you view a webpage, you are viewing one page. However, that doesn’t mean that only one file was used to create the page. Most modern, dynamic websites would use many files to generate a single page.

Imagine that the WordCap function was defined in the PHP file, page1.php. What would we have to do if we created another page, page2.php and we wanted to use the WordCap function? We would have to make it accessible to that script as well (i.e. define it in that page as well)!

That’s where the beauty of including files comes in. By including files within our web-pages we can define the function once, and use it in all of our web-pages that include the file where the function was defined.

Questions:

  • What sort of ‘user-defined’ functions would you likely want to use across your website?
  • What sort of display features are you likely to have displayed on your web-pages?
//config.php
function WordCap($text)
{
... 
}

page1.php

include 'config.php';

page2.php

include 'config.php';

PHP provides four include directives that can be used to ‘include’ a file.

  • include
  • include_once
  • require
  • require_once

When a file is included, the contents (functions etc) of the file are accessible from the include statement onwards. Thus in the examples above, we must include the config.php file BEFORE we call the WordCap function.

Questions:

  • What is the difference between include and require?
  • How would the #_once statements differ?
  • Do you think it is possible to use this type of code:
include $variable;

Include files don’t only have to contain functions. Many include files actually contain portions of the website! The structure of a typical webpage might look something like this:

//include common functions
include '../config.php';

//include header
include 'header.php';

//------------------------
//Start of Main Content

/* add your webpage content here */

//end of Main Content
//------------------------

//include footer
include 'footer.php';

The header.php file might contain menu items, meta data etc. Stuff that we want shared across all of our web-pages.

The footer.php file would contain all the stuff that appears at the bottom of all web-pages. Copyright info, author info and maybe additional menu links and the closing html tag.

Scope

Variables are only viewable / accessible from the point they are declared, and in the scope that they are defined! For example, variables declared inside the function are not accessible from outside the function and vice-versa. This is why in the WordCap function we ‘return’ the value to the user instead of trying to access the $value variable directly.

However there maybe situations where we want to cross the boundaries of the scoping rules, and PHP provides a mechanism for doing that. We won’t be doing that very often, however we will be introduced to the concept when we start using MySQL.

Questions:

  • How does variable scope help with modular design?
  • Why would we want to violate the scope rules?
  • What sort of dangers are inherit with breaking variable scope?

Operators

All of the programming languages that I know provide operators for the programmer to use. Usually operators are defined for built in data-types, however very advanced and powerful programming languages such as C++ allow the programmer to define the behaviour of operators on a programmer defined data-type.

There are three types of operators that we are covering in this course. Arithmetic, logic and comparative. Arithmetic operators include + - / * for addition, subtraction, division and multiplication. Logic operators include the && || ! for and, or and not. Comparative operators include < > <= != for less than, greater than, less than or equal and not equal.

if($n < 50)
  $grade = 'Failed';

if(!$logged_in)
  return;  

$total = $qty * $price;
if($total > 100)
  {
  $discount = $total * $discount_percentage;
  $total = $total - $discount;
  }

In many cases, operators are used as part of an expression rather than a statement. User-defined functions can also be used as part of an expression instead of a statement.

//Example One
$logged_in = FLogged_in();
if(!$logged_in)
  return;

//Example Two
if(!FLogged_in())
  return;

Questions

  • Do the two examples achieve the same goal?
  • Where would you want to use one technique over the other?
  • Where could this all fall over?
  • Why did I name the function FLogged_in instead of Logged_in?