Skip to content

This 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

PHP Logo

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.

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:

<?php
declare(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.

To get to know PHP you can write small scripts and run them from the command line:

php -f filename.php

You 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:

<?php
2 + 2;
// 4

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 property

PHP uses $ to prefix all variable names.

When calling a function, parentheses around the arguments are required:

<?php
echo("Hello World");
echo "Hello World"; // echo is special, parens optional

PHP scoping in functions is unusual: global variables are not available inside the function body, unless “invited” into the function with global.

$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

$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

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);

Functions in PHP require an explicit return statement to return a value. Without it, they return null:

<?php
function f(int $a, int $b): string {
return "x";
}
$s = f(1, 42); // returns "x"

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-object

The Operator ?-> (introduced in PHP 8.0) avoids this error. It is called the “nullsafe operator”:

<?php
$a?->b?->c;
// null

PHP 8 introduced significant improvements to the type system. All basic data types can now be declared explicitly:

  • null
  • bool - true or false
  • int - integers
  • float - floating point numbers
  • string - text
  • array - ordered maps
  • object - generic objects

Since PHP 7.1, you can mark types as nullable using ?:

<?php
function getUser(?int $id): ?User {
if ($id === null) {
return null;
}
// ... find user
}

Since PHP 8.0, you can declare union types:

<?php
function 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:

<?php
enum Status {
case Pending;
case Active;
case Archived;
}
function setStatus(Status $status): void {
// ...
}
setStatus(Status::Active);

Enums can also have values (backed enums):

<?php
enum Status: string {
case Pending = 'pending';
case Active = 'active';
case Archived = 'archived';
}
echo Status::Active->value; // "active"

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 = <<<EOM
This is a so called "Heredoc"
it can contain many lines of text
and 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); // ABC
echo strtolower($s); // abc
echo 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 in PHP are ordered maps - they can use both integer and string keys:

<?php
$a = ["this", "that", "something"];
$a = array("this", "that", "something"); // older syntax
echo $a[0]; // "this"
<?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"
];

PHP has many built-in functions that work on arrays:

<?php
$numbers = [1, 2, 3, 4, 5];
count($numbers); // 5
array_sum($numbers); // 15
array_reverse($numbers); // [5, 4, 3, 2, 1]
in_array(3, $numbers); // true
// Adding elements
$numbers[] = 6; // append
array_push($numbers, 7); // append
array_unshift($numbers, 0); // prepend

PHP supports three visibility modifiers for class properties and methods:

<?php
class 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() {}
}

PHP 8.0 introduced constructor property promotion, which reduces boilerplate code when defining classes:

<?php
class 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;
}
}
<?php
class 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.

The basic if statement works like in most programming languages:

<?php
if ($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"
};

The traditional switch statement is also available:

<?php
switch ($x) {
case 1:
case 2:
echo "One or Two";
break;
case 3:
echo "Three";
break;
default:
echo "Something else";
}

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 null

PHP offers several ways to iterate over arrays:

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";
}

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);
// 15
$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
);
$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);

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 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/"
}
}
}

PHP uses exceptions for error handling:

<?php
try {
$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:

<?php
if ($value < 0) {
throw new InvalidArgumentException('Value must be positive');
}

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 {
// ...
}
}

Laravel makes heavy use of attributes for routing, validation, and dependency injection:

<?php
use Laravel\Component\Routing\Annotation\Route;
class BlogController {
#[Route('/blog/{id}', name: 'blog_show')]
public function show(int $id): Response {
// ...
}
}

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 {
// ...
}

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"; }