🎁GET 25% OFF Learning PHP Using Code 👉CANADA👈 Until Canada Day 2024🎁

Basic Use Of Exceptions

Exceptions can be thrown and caught. Surround code in a try block. If an exception is thrown and its current function scope has no catch block, the exception will “bubble up” the call stack to the calling function until it finds a matching catch block. All finally blocks it encounters along the way will be executed.

Sample Code <?php
function divNumbers ($num1$num2) {
    if (
$num2 === 0) {
        throw new 
Exception("Division by zero invalid");
    }
    return (
$num1/$num2);
}

try {
  
$num divNumbers(20);
} catch (
Exception $e) {
  echo 
"Error: " $e->getMessage();
  
$num 0;
}
echo 
"\nNumber is {$num}";
?>
Sample Code <?php
function checkNumbers ($num1$num2) {
    if (
$num1 !== $num2) {
        throw new 
Exception("Wrong answer!");
    }
    return (
$num1);
}

try {
  
$num checkNumbers(20);
} catch (
Exception $e) {
  echo 
"Error: " $e->getMessage();
  
$num 0;
}
echo 
"\nNumber is {$num}";
?>
Sample Code <?php
function inverseNumbers ($num1) {
    if ( !
$num1 ) {
        throw new 
Exception("Cannot divide by zero!");
    }
    return (
1/$num1);
}

try {
  
$num inverseNumbers(0);
} catch (
Exception $e) {
  echo 
"Error: " $e->getMessage();
  
$num 0;
} finally {
    echo 
"Finally."; // This will be always be executed
}
echo 
"\nNumber is {$num}";
?>
Type Code Here

Extend

A class can inherit constants, methods and properties of another class by using keyword extends.

Sample Code <?php
class ExtendClass extends SimpleClass
{
    
// Redefine the parent method
    
function displayVar()
    {
        echo 
"Extending class\n";
        
parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>
Type Code Here

Class Declaration

An object is created by an executed constructor function of the class. The class defines how objects behave, providing initial values as member variables and implementations of behaviour via member functions. Use public and private modifiers to define if functions can be used outside the object.

Sample Code <?php
class SimpleClass
{
    
// property declaration
    
public $var 'a default value';

    
// method declaration
    
public function displayVar() {
        echo 
$this->var;
    }
}
$instance = new SimpleClass();
// This can also be done with a variable:
$className ‘SimpleClass';
$instance = new $className(); // new SimpleClass()
?>
Sample Code <?php
class Foo
{
    public 
$bar;

    public function 
__construct() {
        
$this->bar = function() {
            return 
42;
        };
    }
}
$obj = new Foo();
echo (
$obj->bar)(), PHP_EOL;
?>
Type Code Here

Function Declaration

A function is a unit of code that represents a sequence of statements. Functions can accept arguments or values and return a single value (or not).

Sample Code <?php
/* Function That Returns Age Based On Provided Birth Year
    The return type is string.
    The name of the function is myAge
    The number of arguments to the function is 1:
        The first argument is of type int.
 */
function myAge(int $birthYear): string
{
    
// calculate the age by subtracting the birth year from the current year.
    
$yearsOld date('Y') - $birthYear;

    
// return the age in a descriptive string.
    
return $yearsOld . ($yearsOld == ' year' ' years');
}

echo 
'I am currently ' myAge(1995) . ' old.';
?>
Type Code Here

Do while Loop

Checks if condition is true after executing a block of code in the loop. The block of code inside the loop will be executed at least once.

Sample Code <?php
$counter 
0;
do {
    
$counter += 1;
    echo 
"Executing - counter is $counter.\n";
} while (
$counter 10);
?>
Sample Code <?php
$even_numbers 
= [2,4,6,8,10];
$counter 0;
do {
    echo 
$even_numbers[$counter] . "\n";
    
$counter +=1;
} while (
$counter count($even_numbers))
?>
Type Code Here

While Loop

While loop executes a set of statements as long as a condition is true. It requires relevant variables to be ready such as an indexing variable to iterate through a loop.

Sample Code <?php
$counter 
0;

while (
$counter 10) {
    
$counter += 1;
    echo 
"Executing - counter is $counter.\n";
}
?>
Sample Code <?php
$even_numbers 
= [2,4,6,8,10];
$counter 0;
while (
$counter count($even_numbers)) {
    echo 
$even_numbers[$counter] . "\n";
    
$counter +=1;
}
?>
Type Code Here

Foreach Loop

Foreach works only on arrays and objects iterating and providing a specific variable one at a time.

Sample Code <?php
$even_numbers 
= [2,4,6,8,10];
foreach ($even_numbers as $even_number) {
  echo 
$even_number "\n";
}
?>
Sample Code <?php
$array2D 
= [["Ford","F-Series",1984],["GMC","C-Series",1986]];
foreach ($array2D as $key => $data) {
  echo 
$data "\n";
}
?>
Type Code Here

For Loop

The for loop is C-style in that it requires three parts, the initialization or loop variant, the condition and advancement to next iteration. It is used to iterate over data when referring to a changing index.

Sample Code <?php
$even_numbers 
= [2,4,6,8,10];
for ($i 0$i count($even_numbers); $i=$i+1) {
    
$even_number $even_numbers[$i];
    
echo $even_number "\n";
}
?>

The initialization is the iterator variable $i which begins at zero.

The condition is evaluated in every loop and stops when the $i is larger than the length of the array.

The advancement to next iteration is the incrementalism of $i by one.

Type Code Here

Multidimensional Arrays

Multidimensional arrays are two or more levels deep containing one or more arrays.

Sample Code <?php
$students 
= [
    
"john_doe" => [
        
"name" => "John",
        
"surname" => "Doe",
        
"age" => 25,
    
],
    
"jane_doe" => [
        
"name" => "Jane",
        
"surname" => "Doe",
        
"age" => 25,
    
]
];
print_r($people);
echo 
$people["john_doe"]['surname'];
?>
Type Code Here

Two-dimensional Arrays

A two-dimensional array is an array of arrays requiring two indices to select an element.

Sample Code <?php
$int_array2D 
= [ [11,22,33], [111,222,333] ];
$array2D = [ ["Ford","F-Series",1984], ["GMC","C-Series",1986] ];
var_dump($int_array2D);
var_dump($array2D);
echo 
$int_array2D[0][1] . " ";
echo $array2D[0][1];
?>
Type Code Here