0% found this document useful (0 votes)
6 views

SEN 211(PHP)

The document provides an introduction to programming concepts, specifically focusing on PHP, including its syntax, variables, control structures, and the importance of programming languages. It explains the basics of PHP, such as setting up a development environment, outputting content, and using variables, as well as control structures like conditional statements and loops. Additionally, it covers advanced topics like concatenation, constants, and the differences between switch and match expressions in PHP.

Uploaded by

Doctor krystyne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

SEN 211(PHP)

The document provides an introduction to programming concepts, specifically focusing on PHP, including its syntax, variables, control structures, and the importance of programming languages. It explains the basics of PHP, such as setting up a development environment, outputting content, and using variables, as well as control structures like conditional statements and loops. Additionally, it covers advanced topics like concatenation, constants, and the differences between switch and match expressions in PHP.

Uploaded by

Doctor krystyne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

Week 1

SEN 102 Principles of


Programming I
Software Engineering,
Department of Computing Science,
Faculty of Science,
Admiralty University of Nigeria (ADUN),
Delta State.

Lecturer: Bernard Ephraim


Introduction to Programming Concepts
What is Programming?
Programming is the process of creating instructions for a
computer to perform specific tasks.
Itinvolves writing code using a programming language to
solve problems and automate tasks.
A computer program is a sequence or set of instructions in
a programming language for a computer to execute.
Computer programs are one component of software,
which also includes documentation and other intangible
components.
Programming Languages
A programming language is an artificial language that can be used to control
the behaviour of a machine, particularly a computer
 It can also be described as a system of notation for writing computer
programs.
 Each programming language is described by it syntax (structure) and
semantics (meaning).
 A statement is a syntactic unit of an imperative programming language that
expresses some action to be carried out
 It can also be described as a a single line of code that performs a specific
task.
 There are various programming languages available, each with its own syntax
and purpose. Examples include C++, Java, Python, and PHP.
 PHP is widely used for web development.
PHP (HyperText Pre-Processor)
Why Learn PHP?
Learning PHP offers several benefits:
1. It is popular for web development, powering a large portion of
websites.
2. PHP has a vast community and extensive documentation, making it
easy to find support and resources.
3. It is beginner-friendly and has a gentle learning curve, making it a
good language to start with.
Setting Up a Development Environment
 To work with PHP, you need a development environment.

 One option is
1. XAMPP - https://www.apachefriends.org/download.html,
2. WAMP - https://www.wampserver.com/en/download-wampserver-64bits/#download-
wrapper, or
3. Laragon - https://laragon.org/download/index.html
 The above packages provide a PHP stack with Apache, MySQL, and PHP itself.
1. Apache – is the file server
2. MySQL – the database management system
3. PHP – the programming language
 Install and configure one of these environments on your computer.
PHP Syntax Basics
PHP:
 files are saved with the .php file extension. Example drawing.php
 code is enclosed in opening and closing tags: <?php and ?>. This tells the server
that the code within is PHP. Always ensure proper syntax by using opening and
closing tags correctly.
Example
<?php
echo "my first code";
?>
 statements are terminated with a semi-colon (;)
Example echo "my first code";
 expresses a group of code to be treated as a block using braces or curly brackets ({})
Outputting Content to Screen
 with echo: Use the echo statement to  with print_r: is specially used to output
output content to the screen. an array or object to the screen. More on
 For example, arrays later.

<?php <?php
echo "Hello, World!"; $array = array(
?> 'name'=>'John',
 will display "Hello, World!" on the webpage 'age'=>'12' );
 with print: alternatively you can use the print_r($array);
print statement to output content to the ?>
screen.
 For example,
<?php
print('my name');
?>
Variables
 Variables are structures used to store data that can be updated in a computer’s
working memory.
 Variables are supported by programming languages like PHP, Java, JavaScript, etc

 They can hold values such as numbers, texts, arrays and so on.

Rules for Creating Variables in PHP


1. Variables denoted with a name that must start with the dollar ($) sign
2. Variable names can be alphanumeric.
3. Special characters are not allowed in variable names except the underscore (_)
4. The dollar ($) sign must be followed by either an underscore or alphabet but not a
number
5. It is preferable to compose variable names with small letters.
6. Use underscores to replace spaces in variable names
7. Variables are assigned values using the equality sign (=) followed by the value
Variable Types
 A type or variable type is the kind of data a variable can hold.

 Each programming language has its own supported types and most of them are
identical.
 PHP has different variable types, including

1. strings (text),
2. integers (whole numbers),
3. floats (decimal numbers),
4. Boolean,
5. Array,
6. Object,
7. NULL,
8. Resource and so on
Concatenation and Interpolation
 Concatenation – implies combining  Interpolation – implies inserting
strings together to form complex variables directly into double quoted
strings. strings to form complex strings
without the need of the dot (.)
 In PHP concatenation is achieved operator.
using the dot (.) operator.
 Example
 For example,
<?php
<?php
$name = "John";
$name = "John";
$age = 12;
$greeting = "Hello, " . $name;
$greeting = "$name is $age years
?> old.";
 will create the string "Hello, John". ?>
 will create the string "John is 12 years
old.".
Constants in PHP
 Constants like variables are structures for storing values, but their values cannot be changed once
defined.
 Constants are useful for storing values that remain constant throughout the program.
 Use define(name,value) to create a constant, providing a name and value.
 By convention constants are denoted by capital letters.
 You can call a constant by writing its name without quotation marks or constant('name')
 Example
<?php
define('PIE', 1.42);
define('FRUIT','Mango');
print("PIE: ".PIE);
print("FRUIT: ".constant('FRUIT'));
?>
Questions & Answers
Week 2

SEN 102 Principles of


Programming I
Software Engineering,
Department of Computing Science,
Faculty of Science,
Admiralty University of Nigeria (ADUN),
Delta State.

Lecturer: Bernard Ephraim


Control Structures: Conditional Statements
& Loops
What are Control Structures?
Control Structures are at the core of programming logic.
They allow a script to react differently depending on what
has already occurred, or based on user input, and allow
the graceful handling of repetitive tasks.
In PHP, there are two primary types of Control Structures:
1. Conditional Statements and
2. Control Loops
Conditional Statements
Conditional Statements
Conditional statements are statements that allow us to
execute a particular block of code once if a condition is met.
There are different kinds of conditional statement:
1. If statements
2. If…else statements
3. If…elseif…else statements
4. Switch statements
5. Match statement
If statements
 This is the basic form of conditional statements.
 Its usage is based on the common day-to-day usage of if statements in
natural language.
 For instance, you can tell your friend to get a you a bottle of coke if it is
chilled.
 In the case above if your friend finds out from the seller that his stock of
coke drink is not chilled, he is obliged not to buy.
 The following syntax is used to infer the if statement in PHP and most
programming languages
if (condition) {
code to be executed if condition is true;
}
If statements cont’d
 The condition in the example above is the state of the coke drink being child
 Hence we can represent this condition by is_chilled?
if (isChilled){
//get coke
}
 Example
$isChilled = true;
if($isChilled){
echo 'get coke';
}
If…else Statements
 When we critically look at most use-cases of the if statement in natural language an alternative is
usually provided when the condition is not met.
 In our example above, you could ask your friend to get you ice-scream instead of available coke is
not chilled.
 This would be like this in plain English “get me a bottle of coke if it is chilled else get me one bottle
water”.
 Notice the use of else – this is similar in the case of PHP and other programming languages
$isChilled = false;
if($isChilled){
echo 'get coke';
}else{
echo 'get one bottle water';
}
If…elseif…else Statements $isChilled = false;
 What if you have more than one $isBiscuitAvailable=false;
alternative for the chilled coke? if($isChilled){
Then you find yourself telling the
your friend a series of or else if or echo 'get coke';
else if statement. }elseif($isBiscuitAvailable){
 For example this would tell your echo 'get one bottle water and
friend to get chilled coke or a biscuit';
bottle of water and biscuit if biscuit }else{
is available else candy.
echo 'get candy';
}
If…elseif…else Alternate Syntax Example
 An alternate syntax for the if $a=5;
statement is to replace the if ($a == 5):
opening curly brackets ,{, with
colon ,:, and end the if statement echo "a equals 5...";
with the endif; and a semi-colon. elseif ($a == 6):
 This can be useful in conditionally echo "a equals 6!!!";
outputting html within php else:
statement
echo "a is neither 5 nor 6";
$a=5;
endif;
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
Switch
 Its syntax is:  alternative syntax:
 The switch statement is similar to a
series of IF statements on the same switch ($variable) { switch ($variable):
expression.
case 'value': case 'value':
 In many occasions, you may want to
compare the same variable (or # code... # code...
expression) with many different values, break; break;
and execute a different piece of code
depending on which value it equals to. default: default:
 This is exactly what the switch statement # code... # code...
is for.
break; break;
 It is a special case of the if…elseif
statement and often cleaner form of } endswitch;
expression.
Switch Cont’d  Example
switch (1) {
 In the sample code above, the
variable $variable is compared with case 1:
the values appended to the case echo '1';
statement.
case 2:
 Ifa match is found the code starts
executing from that point downwards echo '2';
through the whole switch statement. case 3:
echo '3';
}
Switch Cont’d  Example
switch (1) {
 One use case for this continuous
downward execution of code could case 1:
be when two or more case conditions case 2:
have the same implementation then
stacking the cases together would echo '2 and two';
help prevent repeating yourself }
Switch Cont’d  Example
switch (1) {
 To prevent this continuous
case 1:
downward execution of code from
happening we use the break echo '1';
statement at the end of every case break;
block case 2:
echo '2';
break;
case 3:
echo '3';
break;
}
 Example
Switch Cont’d switch (10) {
 When no match is found a default case 1:
block can be defined to be executed echo '1';
according to your need
break;
case 2:
echo '2';
break;
case 3:
echo '3';
break;
default:
echo 'default';
break;
}
$x = 2;
Switch Cont’d switch ($x+1) {
 Both the switch condition and the case 1:
case match can be expressions echo '1';
break;
case 2:
echo '2';
break;
case 3:
echo '3';
break;
default:
echo 'default';
break;
}
Match
 The match expression branches evaluation based on an identity check of a value.

 Similarly
to a switch statement, a match expression has a subject expression that is
compared against multiple alternatives.
 Unlike switch, it will evaluate to a value much like ternary expressions.

 Unlike switch, the comparison is an identity check (===) rather than a weak equality
check (==).
 Match expressions are terminated with a semi-colon

 Syntax,

$return_value = match (subject_expression) {


single_conditional_expression => return_expression,
conditional_expression1, conditional_expression2 => return_expression,
};
Match Cont’d
 Example,

$food = 'cake';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
Match Cont’d
 The list of options in the matches must be exhaustive.

 The code below will produce an UnhandledMatchError error, since the value of
food equal to beans does not exist in the match list
$food = 'beans';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
Match Cont’d
 To solve this problem, just as in the switch statement use the default statement
to handle no matched cases.
$food = 'beans';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
default=>'no match found'
};
var_dump($return_value);
Match Cont’d  Example

$food = 'lime';
 When the implementation of one or
more matches is the same the match $return_value = match ($food) {
expression can be separated by commas 'apple' => 'This food is an apple',
and the implication sign pointing to the
common expression they evaluate to: 'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
'orange','lemon','lime' => 'This is a kind
of citrus',
default=>'no match found'
};
var_dump($return_value);
Match Cont’d  Example

$age = 13;
 You can also match a Boolean true or
false with the outcome of an expression $result = match (true) {
that evaluate to the Boolean type. $age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
var_dump($result);
Switch Vs Match
 The match expression is similar to a switch statement but has some key
differences:
1. A match arm compares values strictly (===) instead of loosely as the
switch statement does.
2. A match expression returns a value.
3. match arms do not fall-through to later cases the way switch
statements do.
4. A match expression must be exhaustive.
Control Loops
Control Loops
 Loopsin PHP and other programming languages are control structures
used to execute the same block of code a specified number of times.
 Some control loops cause a repeated execution of a specified block of
codes while a condition remains true thus called while and do-while
loops.
 Otherscause the repetition over a specified number of counts hence
the name for loop.
 Another causes repetition over the iteration items in an array or array-
like structures hence, foreach loop.
While Loops
 These loops cause the repeated execution of a nested block of code
given that a condition holds true.
 It tells PHP to execute the nested statement(s) repeatedly, as long as the
while expression evaluates to true.
 Its syntax:  Alternate syntax:
while (expr){ while (expr):
statement statement
... ...
} endwhile;
While Loops Cont’d
 Forexample, we can display the count from
value 1 until x is greater than 10
$x = 0;
while($x <= 10){
echo $x;
$x = $x + 1;
}
While Loops Cont’d Example

 Note: to avoid having an infinite loop $x = 0;


(that is, a loop that runs for ever) while($x <= 50){
ensure you have a way of modifying the if($x == 45) {
condition the while statement depends
on such that a logical termination of break;
the loop can be attained; }
 To terminate and exit a while loop or echo $x;
other kinds of control loops
$x = $x + 1;
prematurely use the break; statement
as seen: }
Do-While Loops Example

 Similarto the while loop but differ in $x = 0;


the sense that the code block to be do{
repeated is executed at least once echo $x;
before evaluating the conditional
statement. $x = $x + 1;
 Thus, the statement is executed at least }while($x >= 50);
once whether the condition evaluates
to true or false.
For Loops Example
 Thisloops repeats a block of code until for ($i = 1; $i <= 10; $i++) {
a certain condition is met
echo $i;
 The loop works by counting from a
initial value (expr1) and incrementing it }
based on a defined expression (expr3)
until it reaches a predefined value
(expr2) at which the loop is terminated.
 Oneach count the code in the loop is
executed
for (expr1; expr2; expr3){
statement
}
For Loops Cont’d
 Tocreate an infinite for loop just replace the three expressions with
spaces.
Example
for ( ; ; ) {
echo 'yes';
}
For Loops Cont’d Correct Way:

 While expressions are allowed to $people = array(

be used as arguments to the for array('name' => 'Kalle', 'salt' => 856412),
loops, the cost of evaluating this array('name' => 'Pierre', 'salt' => 215863)
expressions should not be );
expensive $size = count($people);
for($i = 0, $i < $size; ++$i) {
 Wrong way:
$people[$i]['salt'] = mt_rand(000000, 999999);
$people = array(
}
array('name' => 'Kalle', 'salt' => 856412),
array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = count($people); $i < $size; ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);
}
Foreach Loops
 The foreach construct provides an easy way to iterate over arrays.
 foreach works only on arrays and objects, and will issue an error when
you try to use it on a variable with a different data type or an
uninitialized variable.
 There are two syntaxes:

foreach (iterable_expression as $value){


statement
}
foreach (iterable_expression as $key => $value){
statement
}
Foreach Loops Cont’d
Unsetting A Variable:
 Example

$arr = array(1, 2, 3, 4);


$arr = array(1, 2, 3, 4);
foreach ($arr as $key => $value) {
foreach ($arr as $key =>
echo "{$key} => {$value}, "; $value) {
} echo "{$key} => {$value}, ";
 Note: that the variable $value has its last value
retained even after exiting the foreach loop.
}
 This can become a problem when passing that unset($value);
argument by reference as any modification to the
variable leads to modifications in the array. echo $value;
 Solution is to unset the variable $value after exiting
the foreach loop
Foreach Loops Cont’d $array = [
 Unpacking Nested Arrays With list() [1, 2],
 It is possible to iterate over an [3, 4],
array of arrays and unpack the ];
nested array into loop variables foreach ($array as list($a, $b)) {
by providing a list() as the value.
// $a contains the first element of the nested array,
 For example: // and $b contains the second element.

echo "A: $a; B: $b\n";


}
Questions & Answers
Week 3

SEN 102 Principles of


Programming I
Software Engineering,
Department of Computing Science,
Faculty of Science,
Admiralty University of Nigeria (ADUN),
Delta State.

Lecturer: Bernard Ephraim


Introduction to functions in PHP
What is a Function?
 A function is any block of code which executes only when called.
 It is a “chunk” of code that you can use over and over again, rather than writing it out multiple
times.
 Functions in PHP are similar to those in other programming languages.
Characteristics:
 They are only executed when explicitly called and not when declared.
 They enable programmers to break down or decompose a problem into smaller chunks, each of
which performs a particular task.
 They may take from as many as zero to any number of arguments
 They can be made to return a value using the return statement
 When they return a value, they can be used in an expressions
 They can be declared within conditional statements and used outside that scope, though only
callable after the code block. This is not an ideal way of declaring a function
 They have global scope, hence can be declared within another function and called globally. The
caveat is that parent function must be called first before the child function may be called.
Creating a Function
Functions are created using the function keyword followed
by the desired name of the function followed by parenthesis
() which may contain the arguments you specify then a pair
of curly brackets {} containing the block of code to be
executed.
Syntax
function name_of_function ($arguments){
//code block
}
Examining Function Characteristics
They are only executed when explicitly called and not
when declared.
<?php
function display_greeting (){
echo 'good morning';
}
display_greeting();
 They may take from as many as no to any number of
arguments
<?php
function display_greeting ($name){
echo "good morning {$name}\n";
}
function display_greeting_age ($name,$age){
echo "good morning {$name}! Your age is {$age} I guess..";
}
display_greeting('Jerry');
display_greeting_age('Martha',12);
They can be made to return a value using the return
statement
<?php
function display_greeting_age ($name,$age){
return "good morning {$name}! Your age is {$age} I
guess..";
}
$greeting = display_greeting_age('Martha',12);
echo $greeting;
When they return a value, they can be used in a
expressions
<?php
function display_greeting_age ($name,$age){
return "good morning {$name}! Your age is {$age} I
guess..";
}
echo "Hi ". display_greeting_age('Juliet',15);
 They enable programmers to break down or decompose a
problem into smaller chunks, each of which performs a
particular task.
<?php
function display_greeting ($name){
echo "good morning {$name}\n";
}
display_greeting('Jerry');
display_greeting('Martha');
display_greeting('Onyeka');
 They can be declared within conditional statements and used
outside that scope, though only callable after the code block.
This is not an ideal way of declaring a function
<?php
if(false){
function display_greeting_age ($name,$age){
return "good morning {$name}! Your age is {$age} I guess..";
}

}
echo "Hi ". display_greeting_age('Martha',20);
 They have global scope, hence can be declared within another
function and called globally. The caveat is that parent function
must be called first before the child function may be called.
<?php
function parent_function(){
function display_greeting_age ($name,$age){
return "good morning {$name}! Your age is {$age} I guess..";
}
}
parent_function();
echo "Hi ". display_greeting_age('Martha',30);
Type-Hinting Functions
Type-Hinting Functions
A type is the kind of data a variable can hold or a function
can accept as argument or return as value.
Thiscan be integer, string, float etc as declared earlier in
php data types.
Type-hintingsimply refers to specifying the return data type
or arguments of a function or class properties.
To reiterate, type-hinting can only be applied to function
arguments and return values and class properties
Type-Hinting Function Parameters
 To declare the type of any function argument or parameter
specify the type then write the variable name
Syntax
function some_function( type1 $parameter1, type2 $parameter2,...){

}
Type-Hinting Function Parameters
 Example: this returns the full name of an individual given his first name, middle name and
surname
function full_name(string $first_name, string $middle_name, string $surname){
if($middle_name===''){
echo "$surname $first_name";
}else{
echo "$surname $middle_name $first_name";
}
}
full_name('John','','Simon');
Type-Hinting Function Parameters
 Example: this function prints the greeting of the day based on name and time of the
day provided in 24hrs format
function greet(string $name, int $hour){
if ($hour < 12){
echo 'Good morning ';
}elseif($hour < 16){
echo 'Good afternoon ';
}elseif($hour < 20){
echo 'Good evening ';
}else{
echo 'Good night ';
}
echo $name;
}
greet('Lukas',22);
Type-Hinting Function Parameters – Type Test
 Example: to test the types of this function we provide a non-numerical string for the
$hour parameter. This returns a type error message
function greet(string $name, int $hour){
if ($hour < 12){
echo 'Good morning ';
}elseif($hour < 16){
echo 'Good afternoon ';
}elseif($hour < 20){
echo 'Good evening ';
}else{
echo 'Good night ';
}
echo $name;
}
greet('Lukas', 'twelve');
Type-Hinting Function Parameters – Type function greet_with_time(string $name, int $hour){
Coercion echo "It's $hour O'clock! ";
 If we provide a numeric string or float to the $hour if ($hour < 12){
parameter in the greet_with_time function, php
simply converts it to the appropriate integer type. echo 'Good morning ';
 This is called type coercion. }elseif($hour < 16){
 Thus, type coercion refers to the conversion of the echo 'Good afternoon ';
type of a user provided value to the system’s }elseif($hour < 20){
expected data type without throwing an error
provided that the user value can be converted echo 'Good evening ';
character-to-character for strings to integer or float }else{
, truncated from float to integer or “mappable”
from integer to float. echo 'Good night ';
 Note: be careful not to change the type of global }
variables passed by reference as argument to a echo $name. "\n";
function since type coercion can
}
greet_with_time('Lukas','12');
greet_with_time('Lukas',13.50);
Type-Hinting Function Return
 When a function returns a value we can hint the type of its value by writing a colon after the
closing argument parenthesis followed by the type
function greet_with_time(string $name,int $hour):string{
$str= "It's $hour O'clock! ";
if ($hour < 12){
$str .= 'Good morning ';
}elseif($hour < 16){
$str .= 'Good afternoon ';
}elseif($hour < 20){
$str .= 'Good evening ';
}else{
$str .= 'Good night ';
}
return "$str $name";
}
echo greet_with_time('Lukas','12');
Type-Hinting Function Return
 When a function returns a value we can hint the type of this return value by writing a colon after
the function parenthesis followed by the type
function greet_with_time(string $name,int $hour):string{
$str= "It's $hour O'clock! ";
if ($hour < 12){
$str .= 'Good morning ';
}elseif($hour < 16){
$str .= 'Good afternoon ';
}elseif($hour < 20){
$str .= 'Good evening ';
}else{
$str .= 'Good night ';
}
return "$str $name";
}
echo greet_with_time('Lukas','12');
Strict Typing
 From the previous examples you noticed, even though we have declared the
types of the function arguments and/or the return value, we did not get any
errors when we passed values of unexpected types that are coercible or
easily convertible to the required types.
 Forinstance numbers written in strings (sa, ‘10’ or ‘13.56’) would be
converted without errors to the integer (say, 10) or float (say, 13.56) type
without any errors.
 However, numbers written in word form (say, ‘ten’ or ‘one point five’) would
raise an error while being passed to an integer or float type.
Strict Typing Cont’d
 To ensure that the user provides the acceptable type always, we use the strict typing.
 Thus, strict typing would force the user into providing only values of the correct types
or throw an error indicating a type mismatch.
 The PHP compiler in this case would not attempt to convert a number in string form
(say, ‘20’) to the integer form (say, 20) that is compatible with the required type – it
would throw a type error.
 Strict typing in PHP is implemented page-wise and not implied from required or
included files,
 that is, in every page where strict typing is desired a certain line of code (as provided
below) must be written at the top of such page to enforce the desired strict typing.
declare(strict_types=1);
<?php
Strict Typing Function Parameters
declare(strict_types=1);
 Example, the code below would throw a function greet_with_time(string $name,int $hour):string{
type error since the type of the $str= "It's $hour O'clock! ";
argument ‘12’ (string) does not match if ($hour < 12){
the required type of $hour parameter
$str .= 'Good morning ';
which is expected to be integer
}elseif($hour < 16){
$str .= 'Good afternoon ';
}elseif($hour < 20){
$str .= 'Good evening ';
}else{
$str .= 'Good night ';
}
return "$str $name";
}
echo greet_with_time('Lukas','12');
Strict Typing Function Return Values <?php
function greet_with_time1(string $name,int $hour):string{
 Example, the code below shows how
$str= "It's $hour O'clock! ";
PHP throws a type error when the
returned value ($hour) of type if ($hour < 12){
(integer) those not match the $str .= 'Good morning ';
expected return type (string). }elseif($hour < 16){
$str .= 'Good afternoon ';
}elseif($hour < 20){
$str .= 'Good evening ';
}else{
$str .= 'Good night ';
}
return $hour;
}
echo greet_with_time1('Lukas',12);
Strict Typing Functions With No <?php
Return Values function greet_with_time2(string $name,int $hour):void{
echo "It's $hour O'clock! ";
 Example, the code below shows how
to that a PHP function does not if ($hour < 12){
return a value echo 'Good morning ';

 To do this, the void type is used }elseif($hour < 16){


echo 'Good afternoon ';
 Thus, any instance of a return
}elseif($hour < 20){
statement attempting to return a
value of any type found raises an echo 'Good evening ';
error. }else{

 Note: that the return statement echo 'Good night ';


(return;) without any explicit value }
does not through an error in this case return $name;
}
greet_with_time2('Lukas',12);
Strict Typing Functions With Nullable <?php
Return Types function greet_with_time3(string $name,int $hour):?int{
echo "It's $hour O'clock! ";
 A parameter is nullable if its value can be
omitted. if ($hour < 12){
echo 'Good morning ';
 For instance middle names are nullable
as not all people have middle names }elseif($hour < 16){
echo 'Good afternoon ';
 However, first and last names are not
nullable as everyone is expected to have }elseif($hour < 20){
them. echo 'Good evening ';
}else{
 Thus, a nullable return type of say, string,
integer or float is declared by preceding echo 'Good night ';
its declaration with a question mark (?) return $hour;
 In the example present both the integer }
and null types can be returned by the return null;
function without errors. }
greet_with_time3('Lukas',12);
<?php
Strict Typing Functions With Multiple
function greet_with_time4(string $name,int $hour):int|float|null{
Return Types echo "It's $hour O'clock! ";
 You can make a function return one if ($hour < 12){
of given number of types by declaring echo 'Good morning ';
those types separated by pipes (|). return null;
}elseif($hour < 16){
 This is also called the union types echo 'Good afternoon ';
 When $hour is greater than 12 but return 'yes';
less than 16 PHP raises a type error }elseif($hour < 20){
as the type string is not among the echo 'Good evening ';
expected return types of integer, return 16.78;

float and null }else{


echo 'Good night ';
 Note: that multiple types declaration return 15;
can also be applied in a similar way to }
the function parameters }
greet_with_time4('Lukas',14);
<?php
Strict Typing Functions With The
function greet_with_time5(string $name,int $hour):mixed{
Mixed Return Type
echo "It's $hour O'clock! ";
 You can make a function return any if ($hour < 12){
type by using the mixed type. echo 'Good morning ';
 Unlike in the previous example, when return null;
$hour is greater than 12 but less than }elseif($hour < 16){
16 PHP does not raise a type error as echo 'Good afternoon ';
the type string is implied in the return 'yes';
mixed type. }elseif($hour < 20){
 Note: echo 'Good evening ';
return 16.78;
 this may not be the best way to go, }else{
use this only when necessary, else
echo 'Good night ';
declare your types explicitly.
return 15;
 The mixed type is not nullable, that }
is, you cannot put the question mark }
before it (?mixed) greet_with_time5('Lukas',14);
Functions With Optional Parameters <?php
 To make a parameter optional in PHP function get_full_name(string $first_name,string
or other programming languages is to $surname,string $middle_name=''):string{
provide a default value for that if($middle_name===''){
parameter at its declaration.
return "$first_name $surname\n";
 Argument to optional parameters
}else{
may be omitted (that is left blank)
without any cause for alarm. return "{$first_name} {$middle_name}
{$surname}\n";
 However, as a rule of thumb, it is
required that you declare all optional }
parameters after declaring all non- }
optional parameters.
//middle name is omitted
 See example echo get_full_name('Melchizedek','Mohammed');
//middle name is provided
echo get_full_name('Kolawole','Ciroma','Nmesoma');
Declaring Functions Parameters By <?php
Reference $b = 10;
 So far, we have been declaring function $h = 5;
parameters by value function area_of_triangle(int|float &$base, int|float $height,
 What this means is this: if a global string $unit='cm'):string{
variable is passed as argument any of the //this line will change the global state of the variable $b
function parameters that we have
discussed so far, the global state (value) $base = 0.5 * $base;
of that variable remains intact even if the $area = $base * $height;
parameters gets reassigned within the
return "$area $unit sq\n";
function.
}
 However, when we pass a variable by
reference to a function parameter we echo '$b = '.$b."\n";
bring also its global state. echo '$h = '.$h."\n";
 In this case, changes to this parameter in echo area_of_triangle($b,$h);
the function scope would affect the
variable in the global state. //the value of the variable $b has changed
// based on the calculation $base = 0.5 * $base; in the function
 To accept arguments by referecnce
precede your parameter name by an echo '$b = '.$b."\n";
ampersand (&). echo '$h = '.$h."\n";
 See example
Spread Operator and Variadic Functions <?php
 A variadic function is a function which function multiply_everthing(int|float $x, int|float $y,
has variable number of parameters. int|float ...$rest):int|float{
 Spread operator helps us collect into an $product = $x * $y * array_product($rest) ;
array function arguments whose
parameters where not originally declared return $product;
into one parameter by preceding this }
parameter with ellipses (…) or
decompose the items in an array into a /*the arguments 2 and 3 maps to the parameters $x and $y.
number of function arguments by the arguments 4,5,6 and 7 are collected into an array
preceding the array with an ellipses. ([4,5,6,7]) and passed into the function as $rest*/
 In our previous examples, we dealt with echo multiply_everthing(2,3,4,5,6,7)."\n";
functions with fixed number of
parameters and arguments. /*the code below decomposes the $array into six (6)
separate arguments*/
 However, sometimes the total number of
these arguments or parameters may not $array = [2,3,4,5,6,7];
be known before hand, the spread echo multiply_everthing(...$array);
operator and variadic functions help us
solve this problem.
Named Functions Arguments
 Right up to this point we have passed arguments into functions based on the parameter
position in the function declaration,
 That is, if $first_name was declared first and $surname declared second, then the argument
for $first_name must come first before the argument for the $surname.
 This can be costly for the following reason:
 If after building your project with the function illustrated above with several pages of your code
calling that function and a need arises to make changes in the order and maybe number of
parameters in that function, then you have a lot of work to do updating every instance of that
function call within your project.
Named Functions Arguments Cont’d
 The solution is using named arguments.
 Named arguments are declared by writing the name of the associated parameter without
the dollar ($) sign followed by a colon (:) and then the argument
 Note that:
 Named arguments allow us to pass function arguments in any other unlike positioned
arguments.
 Arguments to parameters with default values can also be omitted
 Positional arguments must come before named arguments when mixing both styles in a
function call.
 Calling a named argument more than once raises an error.
Named Functions Arguments Cont’d
<?php
function get_full_name(string $first_name,string $surname,string $middle_name=''):string{
if($middle_name===''){
return "$first_name $surname\n";
}else{
return "{$first_name} {$middle_name} {$surname}\n";
}
}
//in named function arguments the order of the arguments does not matter
echo get_full_name(middle_name:'Melchizedek',surname:'Mohammed',first_name:'Yaqoob');
//in named function arguments default value can be omitted as well
echo get_full_name(surname:'Mohammed',first_name:'Yaqoob');
/*in mixing positional arguments with named arguments, positional
arguments come first
*/
echo get_full_name('Kolawole',middle_name:'Ciroma',surname:'Nmesoma');
//the old way
echo get_full_name('Kolawole','Ciroma','Nmesoma');
Named Arguments and The Spread <?php
Operator function multiply_everthing(int|float $x, int|float $y,
 when mixing the spread operator int|float $z, int|float ...$rest):int|float{
and named function arguments the $product = $x * $y * $z * array_product($rest) ;
spread operator must come first,
return $product;
then the named arguments,
}
 the caveat is, the number of items
in the array plus the total number /*the arguments 2, 3 and 4 map to the parameters $x, $y
of named arguments passed must and $z. the arguments 5,6 and 7 are collected into an array
equal the total number of explicitly ([5,6,7]) and passed into the function as $rest*/
declared parameters. echo multiply_everthing(2,3,4,5,6,7)."\n";
 In this example the number of /*mixing spread operator and named arguments*/
items in the array[4,5] is 2 plus 1
named argument z equates the $array = [4,5];
number of explicitly declare echo multiply_everthing(...$array,z:3);
parameter $x, $y, $z
Variable Functions
 Variable functions provide a way to dynamically call a function by passing its name as string to a
variable and then calling that variable in the normal way that function would have been
legitimately called.
 That is, when a variable is appended by parenthesis ,() PHP would immediately look for the
declared function whose name matches the value of that variable and execute it.
 This is useful in implementing callbacks and function tables.
 Note:
 An error would be thrown if a function dynamically called does not exit.
 To avoid this from happening it is good practice to check for the existence of the function before calling
it by using the is_callable, function_exists or method_exists functions.
 For instance, the code below should print a ‘yes’ when added to the example that follows
if(is_callable('adjacent')){
echo 'yes';
}else{
echo 'no';
}
Variable Functions Example
function hypothenus(int|float $opposite, int|float $adjacent,string $unit='cm'):string{
$h= sqrt($opposite ** 2 + $adjacent ** 2);
return "the hypothenus of the triangle with the for Op = $opposite and Adj = $adjacent is = $h
$unit\n";
}
function opposite(int|float $hypothenus, int|float $adjacent,string $unit='cm'):string{
$o= sqrt($hypothenus ** 2 - $adjacent ** 2);
return "the opposite side of the triangle with the Hyp = $hypothenus and Adj = $adjacent is = $o
$unit\n";
}
function adjacent(int|float $hypothenus, int|float $opposite,string $unit='cm'):string{
$a= sqrt($hypothenus ** 2 - $opposite ** 2);
return "the adjacent side of the triangle with the Hyp = $hypothenus and Adj = $opposite is = $a
$unit\n";
}
Variable Functions Example Cont’d
//functions here are called explicitly
echo hypothenus(3,4);
echo opposite(5,4);
echo adjacent(5,3);
//check against variable functions
echo "\nCompare with the variable function outputs\n";
$name_of_sides =['hypothenus','opposite','adjacent'];
$name_of_function = $name_of_sides[0];
//functions here are called dynamically
echo $name_of_function(3,4);
echo $name_of_sides[1](5,4);
echo $name_of_sides[2](5,3);
Anonymous Functions (Closures)
 Anonymous functions, also known as closures, allow the creation of functions which
have no specified name.
 They are most useful as the value of callable parameters, but they have many other
uses.
 Anonymous functions are implemented using the Closure class.
 When not declared as an argument to a function they are terminated with a semi-colon
(;) and assigned to a variable.
 This variable they are assigned to can be called in the same way as we did with variable
functions.
 Closures may also inherit variables from the parent scope. Any such variables must be
passed to the use language construct. These variables must not include superglobals,
$this, or variables with the same name as a parameter. A return type declaration of the
function has to be placed after the use clause.
Anonymous Functions Cont’d //contents array
//create the anonymous function
$contents_array = [
$create_files = function (array $contents):string{
/*create a variable to hold the directory ['name'=>'Bella','content'=>'My name is
to save your files*/ Bella'],
$dir='./text-files/';
['name'=>'Bello','content'=>'My name is
//check if the directory exists
Bello'],
if(!is_dir($dir)){
mkdir($dir); ['name'=>'Richmond','content'=>'My name
} is Richmond'],
//scan through each item in the $contents array ['name'=>'Olasupo','content'=>'My name is
foreach ($contents as $content) { Olasupo'],
//create a file and save it to the hard disk
file_put_contents('./text-files/'.$content['name'].'.txt',
];
$content['content']);
//call the anonymous function passing its
}
expected argument
return 'done!';
}; echo $create_files($contents_array);
Anonymous Functions With The Use Clause
//using the use clause
$message = 'hello';
// No "use"
$example = function (string $name):string {
//this line would raise an error because $message is not local
return "$message $name";
};
echo $example('Chris');
// Inherit $message
$example = function (string $name) use ($message):string {
return "$message $name";
};
echo $example('Chris');
Arrow Functions
 Arrow functions are more concise syntax for anonymous functions.
 Both anonymous functions and arrow functions are implemented using the Closure class.
 Arrow functions have the basic form fn (argument_list) => expr.
 When a variable used in the expression is defined in the parent scope it will be implicitly
captured by-value.
 Arrow functions support the same features as anonymous functions, except for this differences
as state below:
 Arrow functions unlike anonymous can use variables from the parent scope without the need for
the use clause
 Arrow functions typically allow only one line of code unlike the anonymous functions which allows
the use of multiple lines of code
 Unlike anonymous functions, arrow functions return a value

 In the following example, the functions $fn1 and $fn2 behave the same way.
Arrow Functions Cont’d Example 2 – nested arrow function
$y = 1; $z = 1;
//arrow function $fn = fn($x) => fn($y) => $x * $y + $z;
$fn1 = fn($x) => $x + $y; // Outputs 51
// equivalent to using $y by value: var_export($fn(5)(10));
$fn2 = function ($x) use ($y) {
return $x + $y;
};
var_export($fn1(3));
Questions & Answers
Week 4

SEN 102 Principles of


Programming I
Software Engineering,
Department of Computing Science,
Faculty of Science,
Admiralty University of Nigeria (ADUN),
Delta State.

Lecturer: Bernard Ephraim


PHP Arrays
What is an Array?
 An array in PHP is actually an ordered map.
 A map is a type that associates values to keys.
 This type is optimized for several different uses; it can be treated as
 an array,
 list (vector),
 hash table (an implementation of a map),
 dictionary,
 collection,
 stack,
 queue, and probably more.
 As array values can be other arrays, trees and multidimensional arrays are also possible.
Array Syntax
Arrays can be created using any of the syntaxes below:

$new_array = array(item1, item2, …, itemN);

or
$next_array = [item1, item2, …, itemN];
Array Example
<?php
//this array can be created either this way
$new_array = array('egg', 'rice', 12, 13.56);
print_r($new_array);
//or this way
$next_array = ['egg', 'rice', 12, 13.56];
print_r($next_array);
Types of PHP Arrays
Array Types
There are two types of PHP arrays:
 Indexed and

 associative arrays
Indexed arrays
 thistype of PHP array is similar to list in other programming
languages.
 Its items take on implicit zero-indexed keys
 Example
$indexed_array = ['rice','beans','melon'];
 By default
 rice takes on the index 0
 Beans index 1 and
 Melon index 2
Associative Arrays
 These are similar to dictionaries in order programming languages
 These type of arrays allows an explicit assignment of keys to items (values)
 These keys can be either an integer or string
 Items or values can be of any type
 Example
$associative_array = [
'name' => 'John',
'title' => 'Mr',
'age' => 12
];
 From the above, name, title, and age are the respective keys to the values John, Mr,
and 12.
Rules for Creating Keys
 Arrays key can either be of type int or type string

 Keys of the string type that are valid decimal numbers (integer or float) would
be cast (converted) to the integer (int) equivalent eg ‘1.5’, ‘1’ will be cast to 1 but
‘09’ remains as string
 Keys of the float type will be cast to the int type eg 1.5 will be cast to 1

 Keys of bool type will be cast to the int type equivalent of 1 for true and 0 for
false
 Keys of the null type will be cast to an empty string

 Arrays and objects cannot be used for keys

 If
multiple elements in the array declaration use the same key, only the last one
will be used as all others are overwritten
Overwriting Keys
 In the code below, the value d replaces the value a assigned to the key 1.
 This is so because duplicate keys would lead to an overwriting of the initial value by that which
comes last in the array definition.
 In the case of this example a is first replaced by b which in turn is replaced by c and finally be d
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
print_r($array);
Object Oriented Programming (OOP)
What is Object Oriented Programming?
 Object-oriented programming is about modeling a system as a
collection of objects, where each object represents some particular
aspect of the system.
 Objects contain both functions (or methods) and data.
 An object provides a public interface to other code that wants to use
it but maintains its own private, internal state; other parts of the
system don't have to care about what is going on inside the object.
Classes and Instances
 When we model a problem in terms of objects in OOP, we create abstract definitions
representing the types of objects we want to have in our system.
 For example, if we were modeling a school, we might want to have objects representing
professors.
 Every professor has some properties in common:
 name
 Subject
 grade a paper
 Can introduce themselves to their students at the start of the year
 So Professor could be a class in our system.
 The definition of the class lists the data and methods that every professor has.
Classes and Instances Cont’d
 In pseudocode, a Professor class could be written like this:

class Professor
properties
name
teaches
methods
grade(paper)
introduceSelf()
 This defines a Professor class with:
 two data properties: name and teaches
 two methods: grade() to grade a paper and introduceSelf() to introduce themselves.
Classes and Instances Cont’d
 On its own, a class doesn't do anything.

 A class is a kind of template for creating concrete objects of that type.

 Each concrete professor we create is called an instance of the Professor class.

 The process of creating an instance is performed by a special function called a


constructor.
 We pass values to the constructor for any internal state that we want to initialize
in the new instance.
 Generally, the constructor is written out as part of the class definition, and it
usually has the same name as the class itself
Classes and Instances Cont’d
class Professor
properties
name
teaches
constructor
Professor(name, teaches)
methods
grade(paper)
introduceSelf()
PHP Class Definition <?php

 Basic class definitions begin with the class SimpleClass


keyword class, followed by a class name, {
followed by a pair of curly braces which // property declaration
enclose the definitions of the properties
and methods belonging to the class. public $var = 'a default value';
 The class name can be any valid label,
provided it is not a PHP reserved word. // method declaration
A valid class name starts with a letter or public function displayVar() {
underscore, followed by any number of
letters, numbers, or underscores. echo $this->var;

A class may contain its own constants, }


variables (called "properties"), and }
functions (called "methods").
?>
<?php
Instantiating a Class
$instance = new SimpleClass();
 To create an instance of a class, the new
print_r($instance);
keyword must be used followed by the
name of the class. // This can also be done with a variable:

 The name of the class can be written $className = 'SimpleClass';


directly, written in a string enclosed in a $instance = new $className(); // new
pair of parenthesis or passed as a variable. SimpleClass()
print_r($instance);
$instance = new ('SimpleClass');
print_r($instance);
?>
Class Properties
 Properties in class definitions are what we call variables in normal procedural
programming
 Remember, classes are instantiated as objects and the properties of objects vary.

 Properties are declared at the top of the class definition before method definitions

 A property can be:

1. Static – that is, callable within or outside its class definition without instantiating its
class
2. Private – that is, only accessible by methods within its class definition
3. Public – that is, accessible by methods within and outside its class definition
4. Protected – this is, accessible by methods within the class definition or child class
which extends its class definition
Class Properties Example
$obj = new MyClass();
class MyClass
echo MyClass::$static."\n";
{
echo $obj->public."\n"; // Works
static $static = 'static';
echo $obj->protected."\n"; // Fatal Error
public $public = 'Public';
echo $obj->private."\n"; // Fatal Error
protected $protected = 'Protected';
$obj->printHello(); // Shows Public, Protected and Private
private $private = 'Private';
function printHello()
{
echo $this->static."\n";
echo $this->public."\n";
echo $this->protected."\n";
echo $this->private."\n";
}
}
Class Properties Example Cont’d
class MyClass2 extends MyClass{ $obj2 = new MyClass2();
// We can redeclare the public and echo $obj2->static."\n"; // Works
protected properties, but not private echo $obj2->public."\n"; // Works
public $public = 'Public2'; echo $obj2->protected; // Fatal Error
protected $protected = 'Protected2'; echo $obj2->private; // Undefined
static $static = 'static 2'; $obj2->printHello(); // Shows Public2, Protected2,
function printHello() Undefined
{
echo $this->static."\n";
echo $this->public."\n";
echo $this->protected."\n";
echo $this->private;
}
}
Class Methods
 Methods are the verbs in classes

 They definition activities (functions) that a class can perform.

 Methods are same as functions, the difference being that functions are so-called in
procedural programming and methods in object oriented programming.
 Just like variable visibility, methods can be:

1. Static
2. Public
3. Private
4. Protected
Class Constructors
 A constructor is a special method in a class used to instantiate a class.

 It contains code required to initialize the state of the object to be created.


Questions & Answers

You might also like