PHP

PHP is a popular general-purpose scripting language that is especially suited to web development.

All examples are based on PHP 8.3.

Resources:

How to start

Just create a file with .php extension and run it with php command.

//touch app.php
<?php
echo "Hello, world";
//php app.php

Using docker:

docker run --rm -v .:/app php php app/playground.php

Topics

Variables

//variable
$variable = "hello, world";

//constants
define("HELLO", "Hello World");

Predefined variables

$_SERVER //Server and execution environment information
$_GET //HTTP GET variables
$_POST //HTTP POST variables
$_FILES //HTTP File Upload variables
$_REQUEST //HTTP Request variables
$_SESSION //Session variables
$_ENV //Environment variables
$_COOKIE //HTTP Cookies

πŸ‘‰Predefined Variables

Primitive types

$a = 10;
$b = 10.5;
$c = "hello";
$d = true;
$e = null;
$f = [1, 2, 3];
$g = new stdClass();
$h = fn() => print("Hello, world");
$i = fopen("file.txt", "r");

//get type
$j = gettype($a); //integer
$k = gettype($b); //double
$l = gettype($c); //string
$m = gettype($d); //boolean
$n = gettype($e); //NULL
$o = gettype($f); //array
$p = gettype($g); //object
$q = gettype($h); //object(Closure)
$r = gettype($i); //resource

Casting

//cast to string
$a = (string) 10; //"10"
$b = strval(10); //"10"

//cast to integer
$c = (int) "10"; //10
$d = intval("10"); //10

//cast to float
$e = (float) "10.5"; //10.5
$f = floatval("10.5"); //10.5

//cast to boolean
$g = (bool) 1; //true
$h = boolval(1); //true

Operators

//arithmetics operators
$a = 10 + 5; //15
$b = 10 - 5; //5
$c = 10 * 5; //50
$d = 10 / 5; //2
$e = 10 % 3; //1

//assignment operators
$f = 10;
$f += 5; //15
$f -= 5; //10
$f *= 5; //50
$f /= 5; //10
$f %= 3; //1

//comparison operators
$g = 10 == 10; //true
$h = 10 === "10"; //false
$i = 10 != 5; //true
$j = 10 !== "10"; //true
$k = 10 > 5; //true
$l = 10 < 5; //false
$m = 10 >= 10; //true
$n = 10 <= 5; //false

//logical operators
$o = true && true; //true
$p = true || false; //true
$q = !true; //false

//increment and decrement operators
$r = 10;
$r++; //11
$r--; //10

//concatenation
$s = "Hello" . " " . "World"; //Hello World

//null coalesce
$t = null;
$u = $t ?? "no value"; //no value

//null coalesce assignment
$v = null;
$v ??= "no value"; //no value

//spaceship operator
$w = 10 <=> 5; //1
$x = 5 <=> 10; //-1
$y = 10 <=> 10; //0

//ternary
$z = true ? "show if true" : "show if false"; //show if true

//shorthand ternary
$short1 = false ?: "first"; //first

//shorthand ternary
$short2 = 5 ?: 0; //5

Strings

//simple string
$a = "Hello World";

//concatenation
$d = "Hello" . " " . "World";

//interpolation
$e = "Hello $a";

//escaping
$f = "Hello \"World\"";

//use variable in string
$g = "Hello $a";

//some methods
$h = strtoupper($a); //HELLO WORLD
$i = strtolower($a); //hello world
$j = ucfirst($a); //Hello World
$k = ucwords($a); //Hello World
$l = strlen($a); //11
$m = str_replace("Hello", "Hi", $a); //Hi World
$n = strpos($a, "World"); //6
$o = substr($a, 0, 5); //Hello

πŸ‘‰ String reference

Arrays

//simple array
$a = array(1, 2, 3);

//short array syntax
$b = [1, 2, 3];

//associative array
$c = [ "a" => 1, "b" => 2, "c" => 3 ];

//multi-dimensional array
$d = [
  "a" => [
    "a1" => 1,
    "a2" => 2
  ],
  "b" => [
    "b1" => 1,
    "b2" => 2
  ]
];

//recover from array
$e = $a[0];
$f = $c["a"];
$g = $d["a"]["a1"];

//concatenation
$h = array_merge($a, $b);

//add element
$i = array_push($a, 4);

//remove element
$j = array_pop($a);

//sort
$k = sort($a);

//reverse
$l = array_reverse($a);

//filter
$m = array_filter($a, function ($v) {
  return $v > 1;
});

//map
$n = array_map(function ($v) {
  return $v * 2;
}, $a);

//reduce
$o = array_reduce($a, function ($acc, $v) {
  return $acc + $v;
}, 0);

//count
$p = count($a); //3

Destructuring

$items = [
  'first',
  'second',
  'third',
];

list($first, $second, $third) = $items;

echo $first . "\n";
echo $second . "\n";
echo $third . "\n";

πŸ‘‰ Array reference

Conditional Statements

//if/else
if (true) {
    echo "condition 1 \n";
} elseif (true) {
    echo "condition 2 \n";
} else {
    echo "condition 3 \n";
}

//switch case
$x1 = "two";
switch ($x1) {
  case "zero":
    print "--ZERO-- \n";
    break;
  case "one":
    print "--ONE-- \n";
    break;
  case "two":
    print "--TWO-- \n";
    break;
  default:
    print "default option \n";
}

//ternary
$ternary = true ? "show if true" : "show if false";

//shorthand ternary
$short1 = false ?: "first"; //first
$short2 = 5 ?: 0; //5
$short3 = false ?: 0; //0
$short4 = null ?: 'foo'; //'foo'

//null coalesce
$a = null;
$b = "hello world\n";
$c = $a ?? $b ?? "no value"; //hello world

//pattern matching
$x = 10;
$y = 3;

match ($x <=> $y) {
  0 => print "x equals y\n",
  1 => print "x is greater than y\n",
  -1 => print "x is less than y\n",
};

Loops

//for
for ($i = 0; $i < 10; $i++) {
  echo $i . "\n";
}

//while
$j = 0;
while ($j < 10) {
  echo $j . "\n";
  $j++;
}

//do while
$k = 0;
do {
  echo $k . "\n";
  $k++;
} while ($k < 10);

//foreach
$l = [1, 2, 3];
foreach ($l as $v) {
  echo $v . "\n";
}

//foreach with key
$m = [ "a" => 1, "b" => 2, "c" => 3 ];
foreach ($m as $k => $v) {
  echo $k . " => " . $v . "\n";
}

//break
for ($i = 0; $i < 10; $i++) {
  if ($i === 5) {
    break;
  }
  echo $i . "\n";
}

//continue
for ($i = 0; $i < 10; $i++) {
  if ($i === 5) {
    continue;
  }
  echo $i . "\n";
}

//goto
for ($i = 0; $i < 10; $i++) {
  if ($i === 5) {
    goto end;
  }
  echo $i . "\n";
}

end:
echo "end";

Functions

//simple function
function hello() {
  echo "Hello World\n";
}

//function with parameters
function greet($name) {
  echo "Hello $name\n";
}

//function with default parameters
function greet2($name = "World") {
  echo "Hello $name\n";
}

//function with return
function add($a, $b) {
  return $a + $b;
}

//function with type hint
function add2(int $a, int $b): int {
  return $a + $b;
}

//function with variadic parameters
function sum(...$numbers) {
  return array_sum($numbers);
}

//function with named parameters
function named(int $a, int $b, int $c) {
  return $a + $b + $c;
}

//function with named parameters
named(c: 1, a: 2, b: 3);

//callback
function func($callback)
{
  $callback();
}
func(fn () => print('hello world'));

//passing argument as reference
function addOne(&$value)
{
  $value++;
}
$a = 1;
addOne($a); //2

Closure, Arrow function

In PHP, a closure is essentially an anonymous function that can access variables from the parent scope.

//closure
$closure = function ($name) {
    return "Hello $name\n";
};

//closure using external variable
$message = "Hello, world";
$example = function () use ($message) {
    var_dump($message);
};

//example: calculator using arrow function and pattern matching
$calc = fn($a, $b, $op) => match ($op) {
  '+' => $a + $b,
  '-' => $a - $b,
  '*' => $a * $b,
  '/' => $a / $b,
  default => throw new Exception("Invalid operator"),
};

echo $calc(10, 5, '+'); //15
echo $calc(10, 5, '-'); //5
echo $calc(10, 5, '*'); //50
echo $calc(10, 5, '/'); //2

πŸ‘‰ Anonymous functions

Classes

class Person
{
  //static and constans
  public const REFERENCE = "<Class Person>";
  public static $description = "Person Class";

  //constructor
  public function __construct(
    string $name,
    string $lastname,
    string $age
  ) {
    //properties
    $this->name = $name;
    $this->lastname = $lastname;
    $this->age = $age;
  }

  //static method
  public static function StaticMethod()
  {
    print("A simple static method");
  }

  //method
  public function getFullName()
  {
    return $this->name . ' ' . $this->lastname;
  }

  //generic getter
  public function __get($property)
  {
    if (property_exists($this, $property)) {
      return $this->$property;
    }
  }

  //generic setter
  public function __set($property, $value)
  {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }
    return $this;
  }

  //toString
  public function __toString()
  {
    return $this->name . ' ' . $this->lastname . ' ' . $this->age;
  }
}

//usage
$person = new Person('John', 'Doe', 30);

//accessing properties
echo $person->name; //John
echo $person->lastname; //Doe
echo $person->age; //30

//setting properties
$person->name = 'Jane';
$person->lastname = 'Doe';
$person->age = 25;

//accessing static properties
echo Person::REFERENCE; //<Class Person>
echo Person::$description; //Person Class

//accessing static method
Person::StaticMethod(); //A simple static method

echo $person; //Jane Doe 25

Anonymous class

$person = new class(string $name, int $age)
{
  public function __construct(string $name, int $age)
  {
    $this->name = $name;
    $this->age = $age;
  }

  public function getFullName()
  {
    return $this->name . ' ' . $this->lastname;
  }
};

//usage
$person = new Person('John', 'Doe', 30);
echo $person->getFullName(); //John Doe

Class inheritance

class Person
{
  public function __construct(
    string $name,
    string $lastname,
    int $age
  )
  {
    $this->name = $name;
    $this->lastname = $lastname;
    $this->age = $age;
  }
}

class Hero extends Person
{
  public function __construct(
    string $name,
    string $lastname,
    int $age,
    string $superpower
  ) {

    //parent constructor
    parent::__construct($name, $lastname, $age);

    $this->superpower = $superpower;
  }
}

Abstract Class

abstract class Person
{
  public function __construct(string $name, int $age)
  {
    $this->name = $name;
    $this->age = $age;
  }

  public abstract function introduce();
}

class Hero extends Person
{
  //constructor
  public function __construct(
    string $name,
    int $age,
    string $superpower
  ) {
    parent::__construct($name, $age);
    $this->superpower = $superpower;
  }

  public function introduce()
  {
    return "My name is $this->name and I am $this->age years old";
  }
}

Interfaces

interface Animal
{
  public function makeSound();
  public function run($speed = 0);
  public function eat(callable $callback);
}

//class
class Dog implements Animal
{
  public function makeSound()
  {
    echo "Bark";
  }

  public function run($speed = 0)
  {
    echo "The dog is running at " . $speed . " km/h";
  }

  public function eat(callable $callback)
  {
    $callback();
  }
}

Traits

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

//simple trait
trait Hello
{
  public function sayHello()
  {
    echo 'Hello ';
  }
}

//trait that includes another trait
trait World
{
  use Hello;
  public function sayWorld()
  {
    echo 'World';
  }
}

//trait with static method
trait HelloWorld
{
  public function sayHelloWorld()
  {
    echo 'Hello World';
  }
}

//class that uses the traits
class MyHelloWorld
{
  use Hello, World, HelloWorld;
}
//trait with static methods and properties
trait StaticExample
{
  public static $name = "StaticExample";

  public static function staticMethod()
  {
    return "Static Method";
  }
}

echo StaticExample::$name; //StaticExample
echo StaticExample::staticMethod(); //Static Method
trait TraitExample
{
  public abstract function doSomething();
}

/*
when you use a trait with an abstract method,
you must implement the method in the class
that uses the trait
*/
class ClassExample
{
  use TraitExample;

  public function doSomething()
  {
    echo 'Doing something';
  }
}

Attributes

Attributes are a new feature in PHP 8. They are a way to add metadata to classes, methods, and functions.

#[Attribute]
class ExampleAttribute
{
  private string $message;
  private int $answer;

  public function __construct(string $message, int $answer)
  {
    $this->message = $message;
    $this->answer = $answer;
  }
}

#[ExampleAttribute('Hello', 42)]
class Example
{
}

$reflection = new ReflectionClass(Example::class);
$attributes = $reflection->getAttributes();

foreach ($attributes as $attribute) {
  var_dump($attribute->getName());
  var_dump($attribute->getArguments());
  var_dump($attribute->newInstance());
}

πŸ‘‰ Attributes in PHP 8

Enum

enum status: string
{
  case PENDING = 'pending';
  case PUBLISHED = 'published';
  case STARRED = 'starred';
  case DENIED = 'denied';
}

echo status::PENDING->name //pending;
echo status::PUBLISHED->name //published;
echo status::STARRED->name //starred;
echo status::DENIED->name //denied;

//enum with methods
enum Color
{
  case Red;
  case Green;
  case Blue;
  case Purple;

  //that method can be called on each enum value
  public function printColor()
  {
    match ($this) {
      Color::Red => print("😑 Color: Red \n"),
      Color::Green => print("🀒 Color: Green \n"),
      Color::Blue => print("πŸ₯Ά Color: Blue \n"),
      Color::Purple => print("πŸ‘Ώ Color: Purple \n"),
    };
  }
}

Color::Red->printColor(); //😑 Color: Red
Color::Green->printColor(); //🀒 Color: Green
Color::Blue->printColor(); //πŸ₯Ά Color: Blue
Color::Purple->printColor(); //πŸ‘Ώ Color: Purple

Error Handling

//try catch
try {
  throw new Exception('Error');
} catch (Exception $e) {
  echo $e->getMessage();
}

//custom exception
class CustomException extends Exception
{
  public function errorMessage()
  {
    return "Error: " . $this->getMessage();
  }
}

try {
  throw new CustomException('Error');
} catch (CustomException $e) {
  echo $e->errorMessage();
}

Include, Require

Include and require are used to include a file into the current file, but if the file is not found, include will only produce a warning, while require will produce a fatal error.

//math.php
<?php
$add = fn ($a, $b) => $a + $b;
$sub = fn ($a, $b) => $a - $b;
$mul = fn ($a, $b) => $a * $b;
$div = fn ($a, $b) => $a / $b;
//app.php
<?php
require './file.php';
//include './file.php';

echo $add(1, 2); //3
echo $sub(1, 2); //-1
echo $mul(1, 2); //2
echo $div(1, 2); //0.5

Namespaces

//math.php
namespace Math\Basic {
  class Calc
  {
    public function add($a, $b)
    {
      return $a + $b;
    }
  }
}

namespace Math\Geometry {
  class Triangle
  {
    public function area($base, $height)
    {
      return ($base * $height) / 2;
    }
  }
}
//app.php
require 'file.php';

use Math\Basic\Calc;
use Math\Geometry\Triangle;

$calc = new Calc();
echo $calc->add(1, 2);

$triangle = new Triangle();
echo $triangle->area(3, 4);

Keywords

Data Types

KeywordDescription
arrayArray data type
boolBoolean data type
booleanBoolean data type (alias of bool)
doubleFloating point number (alias of float)
floatFloating point number
intInteger data type
integerInteger data type (alias of int)
nullNull value
objectObject data type
resourceResource data type
stringString data type

Statements and Expressions

KeywordDescription
abstractAbstract class or method
andLogical AND
asAlias in foreach loop
breakExits a loop or switch statement
callableCallable type hint
caseCase in switch statement
catchCatch block in try-catch
classDefines a class
cloneClones an object
constDefines a constant
continueSkips the rest of the current loop
declareSets execution directives
defaultDefault case in switch statement
dieEquivalent to exit()
doDo-while loop
echoOutputs one or more strings
elseAlternative condition in if-else
elseifElse if condition
emptyChecks if a variable is empty
enddeclareEnds declare block
endforEnds for loop
endforeachEnds foreach loop
endifEnds if block
endswitchEnds switch block
endwhileEnds while loop
evalEvaluates a string as PHP code
exitTerminates script execution
extendsExtends a class
finalPrevents class/method overriding
finallyFinally block in try-catch-finally
forFor loop
foreachForeach loop
functionDefines a function
globalGlobal variable scope
gotoJumps to a label
ifIf condition
implementsImplements an interface
includeIncludes and evaluates a file
include_onceIncludes a file only once
instanceofChecks object type
insteadofUsed with traits
interfaceDefines an interface
issetChecks if a variable is set
listAssigns variables as if they were an array
namespaceDefines a namespace
newCreates a new object
orLogical OR
printOutputs a string
privatePrivate access modifier
protectedProtected access modifier
publicPublic access modifier
requireIncludes and evaluates a file
require_onceIncludes a file only once
returnReturns a value from a function
staticDeclares static properties or methods
switchSwitch statement
throwThrows an exception
traitDefines a trait
tryTry block in try-catch
unsetUnsets a variable
useImports a namespace or trait
varDefines a variable (PHP 4, deprecated in PHP 5)
whileWhile loop
xorLogical XOR
yieldReturns a value from a generator

Magic Constants

KeywordDescription
__CLASS__Current class name
__DIR__Directory of the current file
__FILE__Full path and filename of the file
__FUNCTION__Function name
__LINE__Current line number in the file
__METHOD__Class method name
__NAMESPACE__Current namespace
__TRAIT__Current trait name

Compiler-specific Keywords

KeywordDescription
__halt_compilerHalts the compiler execution