CA314 Introduction To Open Source Environment Lecture Notes: Unit 3 Decision Making

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

CA314 Introduction to Open Source Environment

Lecture Notes: Unit 3

Decision Making
PHP provides number of statements that you can use to make decisions:

• ❑ The if statement
• ❑ The else and elseif statements
• ❑ The switch statement

The if Statement
The easiest decision-making statement to understand is the if statement. The basic form of an if construct is as follows:

if ( expression )

// Run this code

// More code here

If the expression inside the parentheses evaluates to true, the code between the braces is run. If the expression evaluates
to false, the code between the braces is skipped.

Here’s a simple real-world example:

$widgets = 23;
if ( $widgets == 23 )
{
echo “We have exactly 23 widgets in stock!”;

Alternative Choice with the else Statement


The if statement allows you to run a block of code if an expression evaluates to true. If the expression evaluates to false, the code
is skipped. You can enhance this decision-making process by adding an else statement to an if construction. This lets you run one
block of code if an expression is true, and a different block of code if the expression is false. For example:

if ( $widgets >= 10 )
{
echo “We have plenty of widgets in stock.”;
}
else
{
echo “Less than 10 widgets left. Time to order some more!”;

You can even combine the else statement with another if statement to make as many alternative choices as you like:

if ( $widgets >= 10 )
{
echo “We have plenty of widgets in stock.”;
}
else if ( $widgets >= 5 )
{
echo “Less than 10 widgets left. Time to order some more!”;
}
else
{
echo “Panic stations: Less than 5 widgets left! Order more now!”;

PHP even gives you a special statement — elseif — that you can use to combine an else and an if statement. So the preceding
example can be rewritten as follows:

if ( $widgets >= 10 )
{
echo “We have plenty of widgets in stock.”;
}
elseif ( $widgets >= 5 )
{
echo “Less than 10 widgets left. Time to order some more!”;
}
else
{
echo “Panic stations: Less than 5 widgets left! Order more now!”;

The switch Statement


Sometimes you want to test an expression against a range of different values, carrying out a different task depending on the value
that is matched.

PHP provides a more elegant way to run these types of tests: the switch statement. With this statement, you include the
expression to test only once, then provide a range of values to test it against, with corresponding code blocks to run if the values
match. Here’s the example:

switch ( $userAction )
{
case “open”:
// Open the file
break;
case “save”:
// Save the file
break;
case “close”:
// Close the file
break;
case “logout”:
// Log the user out
break;
default:
print “Please choose an option”;
}

The first line features the switch statement, and includes the condition to test — in this case, the value of the $userAction variable
— in parentheses. Then, a series of case statements
test the expression against various values: ”open”, ”save”, and so on. If a value matches the expression, the code following the
case line is executed. If no values match, the default statement is reached, and the line of code following it is executed.

Ternary Operator
The symbol for the ternary operator is ?.

Unlike other PHP operators, which work on either a single expression (for example, !$x) or two expressions (for example, $x ==
$y), the ternary operator uses three expressions:

( expression1 ) ? expression2 : expression3;

The ternary operator can be thought of as a compact version of the if...else construct. The preceding code reads as follows: If
expression1 evaluates to true, the overall expression equals expression2; otherwise, the overall expression equals expression3.

Here’s a “real world” example to make this concept clearer:

$widgets = 23;
$plenty = “We have plenty of widgets in stock.”;
$few = “Less than 10 widgets left. Time to order some more!”;
echo ( $widgets >= 10 ) ? $plenty : $few;

Looping
The basic idea of a loop is to run the same block of code again and again, until a certain condition is met. As with decisions, that
condition must take the form of an expression. If the expression evaluates to true, the loop continues running. If the expression
evaluates to false, the loop exits, and execution continues on the first line following the loop’s code block.

You look at three main types of loops in this chapter:

• ❑ while loops
• ❑ do...while loops
• ❑ for loops

The while Statement


The simplest type of loop to understand uses the while statement. A while construct looks very similar to an if
construct:
while ( expression )

// Run this code

// More code here

The expression inside the parentheses is tested; if it evaluates to true, the code block inside the braces is run. Then the
expression is tested again; if it’s still true, the code block is run again, and so on. However, if at any point the
expression is false, the loop exits and execution continues with the line after the closing brace.

The do . . . while Loop


Sometimes it’s useful to be able to run the code in the loop at least once before checking the expression, and this is exactly what
do...while loops let you do. For example, if the expression you’re testing relies on setting a variable inside the loop, you need to
run that loop at least once before testing the expression.

Here’s an example of a do...while loop:

<?php

$width = 1;
$length = 1;
do
{
$width++;
$length++;
$area = $width * $length;
} while ( $area < 1000 );

echo “The smallest square over 1000 sq ft in area is $width ft x $length ft.”;
?>

The for Statement


The for statement is a bit more complex than do and do...while, but it’s a neat and compact way to write certain types of loops.
Typically, you use a for loop when you know how many times you want to repeat the loop. You use a counter variable within the
for loop to keep track of how many times you’ve looped.

The general syntax of a for loop is as follows:

for ( expression1; expression2; expression3 )


{
// Run this code
}
// More code here

As with while and do...while loops, if you only need one line of code in the body of the loop you can omit the braces.
You can see that, whereas do and do...while loops contain just one expression inside their parentheses, a for loop can contain
three expressions. These expressions, in order, are:

• ❑ The initializer expression — This is run just once, when the for statement is first encountered. Typically, it’s used
to initialize a counter variable (for example, $counter = 1)
• ❑ The loop test expression — This fulfils the same purpose as the single expression in a do or do...while loop. If this
expression evaluates to true, the loop continues; if it’s false, the loop exits. An example of a loop test expression would
be $counter <= 10
• ❑ The counting expression — This expression is run after each iteration of the loop, and is usually used to change the
counter variable — for example, $counter++

The break Statement


Normally, a while, do...while, or for loop will continue looping as long as its test expression evaluates to true.
However, you can exit a loop at any point while the loop’s executing by using the break statement. This works just like
it does within a switch construct— it exits the loop and moves to the first line of code outside the loop.

$count = 0;

while ( true )
{
$count++;
echo “I’ve counted to: $count<br />”;
if ( $count == 10 )
break;
}

The continue Statement


The continue lets you prematurely end the current iteration of a loop and move onto the next iteration. This can be useful if you
want to skip the current item of data you’re working with; maybe you don’t want to change or use that particular data item, or
maybe the data item can’t be used for some reason.

Functions
A function — also called a subroutine in some other languages — is a self- contained block of code that performs a specific task.

A function often accepts one or more arguments, which are values passed to the function by the code that calls it. The function
can then read and work on those arguments. A function may also optionally return a value that can then be read by the calling
code. In this way, the calling code can communicate with the function.

Functions are an important part of any programming language for a number of reasons:

• ❑ They avoid duplicating code


• ❑ They make it easier to eliminate errors
• ❑ Functions can be reused in other scripts
• ❑ Functions help you break down a big project
Calling Functions
To call a function, you write the function name, followed by an opening and a closing parenthesis:

functionName()

If you need to pass arguments to the function, place them between the parentheses, separating each argument by commas:

functionName( argument )
functionName( argument1, argument2 )

If a function returns a value, you can assign the value to a variable:

$returnVal = functionName( argument );

Defining Functions
Defining a function is really easy — just use the following syntax:

function myFunc()
{
// (do stuff here)

In other words, you write the word function, followed by the name of the function you want to create, followed by parentheses.
Next, put your function’s code between curly brackets ({}). Here’s a trivial example:

function hello()
{
echo “Hello, world!<br/>”;

Defining Parameters
Functions can optionally accept one or more arguments, which are values passed to the function. To tell PHP that you want your
function to accept arguments, you specify one or more corresponding parameters when you define your function. A parameter is
a variable that holds the value passed to it when the function is called.

To specify parameters for your function, insert one or more variable names between the parentheses, as follows:

function myFunc( $oneParameter, $anotherParameter ) {


// (do stuff here)

}
Returning Values from Your Functions
Functions can return values as well as accept them. To get your function to return a value, you use PHP’s return statement:

function myFunc()

// (do stuff here)

return value;

value can be any expression, so you can use a literal value (such as 1 or false), a variable name (such as $result), or a more
complex expression (for example, $x * 3 / 7).

Static Variables
All variables declared within a function are deleted when the function exits, and created anew when the function is next called.
However, sometimes it’s useful to create a local variable that has a somewhat longer lifespan. Static variables let you do just this.
These types of variables are still local to a function, in the sense that they can be accessed only within the function’s code.
However, unlike local variables, which disappear when a function exits, static variables remember their values from one function
call to the next.

To declare a local variable as static, all you need to do is write the word static before the variable name, and assign an initial
value to the variable:

static $var = 0;

The first time the function is called, the variable is set to its initial value (zero in this example). However, if the variable’s value
is changed within the function, the new value is remembered the next time the function is called. The value is remembered only
as long as the script runs, so the next time you run the script the variable is reinitialized.

OOP Concepts
Objects model the real-world things, processes, and ideas that your application is designed to handle. An object-oriented
application is a set of collaborating objects that independently handle certain activities. There are the basic building blocks that
you can use to create object-oriented applications in PHP.

Classes
A class is a unit of code that describes the characteristics and behaviors of something, or of a group of things. A class called Car,
for example, would describe the characteristics and behaviors common to all cars.
Objects
An object is a specific instance of a class. For example, if you create a Car class, you might then go on to create an object called
myCar that belongs to the Car class. You could then create a second object, yourCar, also based on the Car class.

A class specifies the characteristics that an object will have, but not necessarily the specific values of those characteristics.
Meanwhile, an object is constructed using the blueprint provided by a class, and its characteristics have specific values.

Properties
In OOP terminology, the characteristics of a class or object are known as its properties. Properties
are much like regular variables, in that they have a name and a value (which can be of any type). Some properties allow their
value to be changed and others do not.

Methods
The behaviors of a class — that is, the actions associated with the class — are known as its methods. Methods are very similar to
functions; in fact, you define methods in PHP using the function statement. The methods of a class, along with its properties, are
collectively known as members of the class.

Creating Classes and Objects in PHP


To create a class, you use PHP’s class keyword. Here’s a really simple class:

class Car {
// Nothing to see here; move along

This code simply defines a class called Car that does nothing whatsoever — it merely includes a comment. Notice that a class
definition consists of the class keyword, followed by the name of the class, followed by the code that makes up the class,
surrounded by curly brackets ({ }).

To create an object, you use the new keyword, followed by the name of the class that you want to base the object on. You can
then assign this object to a variable, much like any other value.

Here’s an example that shows how to create objects:

class Car {
// Nothing to see here; move along

$beetle = new Car();


$mustang = new Car();
print_r( $beetle ); // Displays “Car Object ( )”
print_r( $mustang ); // Displays “Car Object ( )”

This code first defines the empty Car class as before, then creates two new instances of the Car class — that is, two Car objects. It
assigns one object to a variable called $beetle, and another to a variable called $mustang.
Creating and Using Properties
Class properties are very similar to variables; for example, an object’s property can store a single value, an array of values, or
even another object.

Understanding Property Visibility


Each property of a class in PHP can have one of three visibility levels, known as public, private, and protected:

Public properties can be accessed by any code, whether that code is inside or outside the class. If a property is declared public, its
value can be read or changed from anywhere in your script

Private properties of a class can be accessed only by code inside the class. So if you create a property that’s declared private,
only methods inside the same class can access its contents. (If you attempt to access the property outside the class, PHP generates
a fatal error.)

Protected class properties are a bit like private properties in that they can’t be accessed by code outside the class, but there’s one
subtle difference: any class that inherits from the class can also access the properties.

Declaring Properties
To add a property to a class, first write the keyword public, private, or protected — depending on the visibility level you want to
give to the property — followed by the property’s name (preceded by a $ symbol):

class MyClass {
public $property1; // This is a public property
private $property2; // This is a private property
protected $property3; // This is a protected property

By the way, you can also initialize properties at the time that you declare them, much like you can with variables:

class MyClass {
public $widgetsSold = 123;

Accessing Properties
Once you’ve created a class property, you can access the corresponding object’s property value from within your
calling code by using the following syntax:

$object->property;
Creating a Method
To add a method to a class, use the public, private, or protected keyword, then the function keyword, followed by the method
name, followed by parentheses. You then include the method’s code within curly braces:

class MyClass {
public function aMethod() {
// (do stuff here)

}}

Calling Methods
To call an object’s method, simply write the object’s name, then the same arrow used for accessing properties (->), then the
method name followed by parentheses:

$object->method();

Here’s a simple example that creates a class with a method, then creates an object from the class and calls the object’s method:

class MyClass {
public function hello() {
echo “Hello, World!”;

}}

$obj = new MyClass;


$obj->hello(); // Displays “Hello, World!”

Inheritance
Inheritance allows you to create classes — known as child classes — that are based on another class: the parent class. A child
class inherits all the properties and methods of its parent, and it can also add additional properties and methods.

To create a child class that’s based on a parent class, you use the extends keyword, as follows:

class Shape {
// (General Shape properties and methods here)

class Circle extends Shape {


// (Circle-specific properties and methods here)

You might also like