SEN 211(PHP)
SEN 211(PHP)
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.
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
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,
$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
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:
}
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 ';
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
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
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.
Properties are declared at the top of the class definition before method definitions
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
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.