PHP
SlidesThis page will focus on PHP - the language - alone.
After finishing this page you will
- understand attributes in PHP
- have an overview of PHP 8’s type system: scalars, nullable, unions and enums
- be able to use Constructor Property Promotion
- be able to use the nullsafe operator
?-> - be able to use Arrow Functions `fn() =>“
- be able to use the match expression instead of switch
- use the datastructures in class \DS for algorithms
- use composer
- use composer audit and composer update
What is PHP
Section titled “What is PHP”PHP is an open source project. It was started in 1995 by Rasmus Lerdorf as “Personal Home Page Tools”. The language is now developed by a large community and stands for “PHP: Hypertext Preprocessor” (a recursive acronym).
PHP was specifically designed for web development and can be embedded directly into HTML. It runs on the server side, generating dynamic web pages.
Modern PHP
Section titled “Modern PHP”PHP is dynamically typed, and started out without type declarations. In the current version PHP 8.5.0 there is support for type declarations in functions arguments and return values, class properties and constants. Local variables like $i in the following example cannot have type declarations:
<?phpdeclare(strict_types=1); // This must be the first line of executable code.
function hello(string $who) { $i = 10; while($i>0) { echo "Hello $who\n"; $i--; }}
hello("World");hello(7);?>There is not compile step in PHP, so the type error caused by hello(7) will be raised at runtime, when the php program is first started.
PHP Basics
Section titled “PHP Basics”To get to know PHP you can write small scripts and run them from the command line:
php -f filename.phpYou can use the interactive shell with php -a.
In this guide we will show PHP code with the <?php tag
and use // for comments and output examples:
<?php2 + 2;// 4Some code conventions
Section titled “Some code conventions”Try to stick to PSR-12: Extended Coding Style Guide.
When you choose names for your variables, classes and methods you should stick to the following conventions:
$theVariable = new SomeClass(); // variables are often written in camelCase (starting lowercase) // classes in PascalCase (starting uppercase)
// method names are written in camelCase$a = $b->getSugar(); // a method that returns something$b->isSueet(); // a method that returns true or false // often starts with 'is' or 'has'$b->setSugar($value); // a method that sets a propertyPHP uses $ to prefix all variable names.
Functions
Section titled “Functions”When calling a function, parentheses around the arguments are required:
<?phpecho("Hello World");echo "Hello World"; // echo is special, parens optionalFunctions
Section titled “Functions”PHP scoping in functions is unusual: global variables are not available
inside the function body, unless “invited” into the function with global.
Classical
Section titled “Classical”$pi = 3.141;$e = 2.718;
function f(int $a, int $b) { global $pi; echo "Hello World"; echo "I have arguments $a and $b"; echo "I can access $pi but not $e";}
f(42, 100);This will give a warning: PHP Warning: Undefined variable $e
Anonymous Function
Section titled “Anonymous Function”$pi = 3.141;$e = 2.718;
$f = function (int $a, int $b) use ($pi): void { echo "Hello World"; echo "I have arguments $a and $b"; echo "I can access $pi but not $e";};
$f(42, 100);This will give a warning: PHP Warning: Undefined variable $e
Arrow Function
Section titled “Arrow Function”PHP 7.4 introduced short arrow functions:
$pi = 3.141;$e = 2.718;
// Arrow functions automatically capture $pi by value.// Notice that $e would also be in scope automatically unless shadowed or avoided.$f = fn(int $a, int $b) => print( "I only have one expression, no echo, no block. " . "I have arguments $a and $b. " . "I can access to both $pi and $e.");
$f(42, 100);Return Value
Section titled “Return Value”Functions in PHP require an explicit return statement
to return a value. Without it, they return null:
<?phpfunction f(int $a, int $b): string { return "x";}
$s = f(1, 42); // returns "x"The Nullsafe Operator
Section titled “The Nullsafe Operator”Imagine you have an Object $a, that has a property b containing
another object, and b has a property c. You can access c through $a->b->c
But if $a is null then you will get an error:
<?php$a->b->c;// Error: Trying to get property 'b' of non-objectThe Operator ?-> (introduced in PHP 8.0) avoids this error. It is called the “nullsafe operator”:
<?php$a?->b?->c;// nullType System
Section titled “Type System”PHP 8 introduced significant improvements to the type system. All basic data types can now be declared explicitly:
Scalar Types
Section titled “Scalar Types”nullbool- true or falseint- integersfloat- floating point numbersstring- textarray- ordered mapsobject- generic objects
Nullable Types
Section titled “Nullable Types”Since PHP 7.1, you can mark types as nullable using ?:
<?phpfunction getUser(?int $id): ?User { if ($id === null) { return null; } // ... find user}Union Types
Section titled “Union Types”Since PHP 8.0, you can declare union types:
<?phpfunction processInput(int|float|string $value): string { return (string) $value;}
processInput(42); // "42"processInput(3.14); // "3.14"processInput("hello"); // "hello"PHP 8.1 introduced enumerations:
<?phpenum Status { case Pending; case Active; case Archived;}
function setStatus(Status $status): void { // ...}
setStatus(Status::Active);Enums can also have values (backed enums):
<?phpenum Status: string { case Pending = 'pending'; case Active = 'active'; case Archived = 'archived';}
echo Status::Active->value; // "active"Strings
Section titled “Strings”PHP offers multiple ways to define strings:
<?php$s = 'just a string of characters';$s = "string with {$theVariable} embedded";$s = "string with {$a + $b} a PHP expression embedded";$s = <<<EOMThis is a so called "Heredoc"it can contain many lines of textand ends with the identifier EOM (that i chose!)but only if it's alone on a line all by itself:EOM;
$s = 'aBC';echo strtoupper($s); // ABCecho strtolower($s); // abcecho ucfirst($s); // ABC (first char uppercase)echo $s[0]; // a (index of character)echo substr($s, 0, 2); // aB (start + length)String concatenation uses the . operator:
<?php"Hello" . " " . "World"; // "Hello World"Arrays
Section titled “Arrays”Arrays in PHP are ordered maps - they can use both integer and string keys:
Indexed Arrays
Section titled “Indexed Arrays”<?php$a = ["this", "that", "something"];$a = array("this", "that", "something"); // older syntax
echo $a[0]; // "this"Associative Arrays
Section titled “Associative Arrays”<?php$h = [ "alice" => "beer", "chris" => "tea", "bob" => "mate"];
echo $h["alice"]; // "beer"You can mix integer and string keys:
<?php$mixed = [ 0 => "first", "name" => "John", 1 => "second"];Array Functions
Section titled “Array Functions”PHP has many built-in functions that work on arrays:
<?php$numbers = [1, 2, 3, 4, 5];
count($numbers); // 5array_sum($numbers); // 15array_reverse($numbers); // [5, 4, 3, 2, 1]in_array(3, $numbers); // true
// Adding elements$numbers[] = 6; // appendarray_push($numbers, 7); // appendarray_unshift($numbers, 0); // prependClasses
Section titled “Classes”Visibility Modifiers
Section titled “Visibility Modifiers”PHP supports three visibility modifiers for class properties and methods:
<?phpclass Example { public $publicProp; // accessible everywhere protected $protectedProp; // accessible in this class and subclasses private $privateProp; // accessible only in this class
public function publicMethod() {} protected function protectedMethod() {} private function privateMethod() {}}Constructor Property Promotion
Section titled “Constructor Property Promotion”PHP 8.0 introduced constructor property promotion, which reduces boilerplate code when defining classes:
Traditional Syntax
Section titled “Traditional Syntax”<?phpclass User { private string $name; private string $email; private int $age;
public function __construct(string $name, string $email, int $age) { $this->name = $name; $this->email = $email; $this->age = $age; }}With Constructor Property Promotion
Section titled “With Constructor Property Promotion”<?phpclass User { public function __construct( private string $name, private string $email, private int $age ) { // Properties are automatically created and assigned }}
$user = new User("Alice", "alice@example.com", 30);This is much more concise and reduces duplication.
Control Flow
Section titled “Control Flow”The basic if statement works like in most programming languages:
<?phpif ($i > 10) { echo 'cannot compute, not enough fingers';} elseif ($i <= 0) { echo 'cannot compute, negative number';} else { echo 'input correct';}The match expression (PHP 8.0) is like a more powerful switch:
<?php$result = match($x) { 1, 2, 3 => "low", 4, 5, 6 => "medium", 7, 8, 9 => "high", default => "unknown"};switch
Section titled “switch”The traditional switch statement is also available:
<?phpswitch ($x) { case 1: case 2: echo "One or Two"; break; case 3: echo "Three"; break; default: echo "Something else";}Ternary Operator
Section titled “Ternary Operator”PHP supports the ternary operator and a null coalescing operator:
<?php$result = $condition ? 'yes' : 'no';
// Null coalescing operator (PHP 7.0)$value = $input ?? 'default'; // use $input if set, otherwise 'default'
// Null coalescing assignment (PHP 7.4)$value ??= 'default'; // assign 'default' only if $value is nullArray Iteration
Section titled “Array Iteration”PHP offers several ways to iterate over arrays:
Foreach Loop
Section titled “Foreach Loop”The most common way to iterate:
<?php$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) { echo $fruit . "\n";}
// With keys$person = ['name' => 'Alice', 'age' => 30];foreach ($person as $key => $value) { echo "$key: $value\n";}From functional progamming
Section titled “From functional progamming”PHP builtin functions for applying (user defined) functions to arrays. These are also called “higher oder functions”:
<?php$numbers = [1, 2, 3, 4, 5];
// Map - transform each element$doubled = array_map(fn($x) => $x * 2, $numbers);// [2, 4, 6, 8, 10]
// Filter - select elements$evens = array_filter($numbers, fn($x) => $x % 2 === 0);// [2, 4]
// Reduce - combine elements$sum = array_reduce($numbers, fn($carry, $x) => $carry + $x, 0);// 15Combining higher oder functions:
Section titled “Combining higher oder functions:”$sumOfDoubledEvens = array_reduce( array_map( fn(int $x): int => $x * 2, array_filter( $numbers, fn(int $x): bool => $x % 2 === 0 ) ), fn(int $carry, int $x): int => $carry + $x, 0);Pipe Operator
Section titled “Pipe Operator”$sumOfDoubledEvens = $numbers |> array_filter(?, fn(int $x): bool => $x % 2 === 0) |> array_map(fn(int $x): int => $x * 2, ?) |> array_reduce(?, fn(int $carry, int $x): int => $carry + $x, 0);Namespaces and Autoloading
Section titled “Namespaces and Autoloading”Modern PHP uses namespaces to organize code:
<?php
namespace App\Controller; // my functions, variables live here
require "src/app/entity/user.php";use App\Entity\User; // I want to use function from this namespace without their Namespace
require "src/app/service/logger.php";class UserController { public function show(User $user) { $logger = new \App\Service\Logger(); $logger->log("Displaying user: " . $user->getId()); // ... }}Autoloading
Section titled “Autoloading”Autoloading automates the “require”, so the code is simplified:
<?php
namespace App\Controller;
use App\Entity\User;
class UserController { public function show(User $user) { $logger = new \App\Service\Logger(); $logger->log("Displaying user: " . $user->getId()); // ... }}Autoloading happens at runtime, lazily, at the exact millisecond the PHP interpreter first tries to use an undefined class, interface, trait, or enum.
Laravel uses Composer for autoloading, following PSR-4:
{ "autoload": { "psr-4": { "App\\": "src/" } }}Error Handling
Section titled “Error Handling”PHP uses exceptions for error handling:
<?phptry { $result = riskyOperation();} catch (SpecificException $e) { // Handle specific exception echo $e->getMessage();} catch (Exception $e) { // Handle any other exception echo "An error occurred";} finally { // Always executed cleanup();}You can throw exceptions:
<?phpif ($value < 0) { throw new InvalidArgumentException('Value must be positive');}Attributes
Section titled “Attributes”Attributes (also called annotations in other languages) were introduced in PHP 8.0. They allow adding metadata to classes, methods, functions, and parameters:
<?php#[Route('/api/users', methods: ['GET'])]class UserController {
#[Cache(ttl: 3600)] public function index(): array { // ... }}Attributes in Laravel
Section titled “Attributes in Laravel”Laravel makes heavy use of attributes for routing, validation, and dependency injection:
<?phpuse Laravel\Component\Routing\Annotation\Route;
class BlogController { #[Route('/blog/{id}', name: 'blog_show')] public function show(int $id): Response { // ... }}Creating Custom Attributes
Section titled “Creating Custom Attributes”You can define your own attributes:
<?php#[Attribute]class MyAttribute { public function __construct( public string $value, public int $priority = 0 ) {}}
#[MyAttribute('important', priority: 10)]class MyClass { // ...}Final Quiz
Section titled “Final Quiz”Which code defines a function in PHP?
-
(int|float $a) => 2 * $a; -
fn(int|float $a) => 2 * $a -
function(int|float $a) => 2 * $a -
function(int|float $a) => { return 2 * $a }
How do you loop over the array $list = ["red", "green", "yellow", "blue"] in PHP?
-
foreach($list, ($color) => { echo $color; }); -
foreach ($color as $list) { echo "Color $color"; } -
foreach ($i = 0; $i < count($list); $i++) { echo "Color $list[$i]"; } -
foreach ($list as $color) { echo "Color $color"; }
Online Resources
Section titled “Online Resources”See Also
Section titled “See Also”Answered: 0 / 0 (0%)
Correct: 0 / 0 (0%)