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
- Primitive types
- Operators
- Strings
- Arrays
- Conditional Statements
- Loops
- Functions
- Closure, Arrow function
- Classes
- Anonymous class
- Class inheritance
- Abstract Class
- Interfaces
- Traits
- Attributes
- Enum
- Error Handling
- Include, Require
- Namespaces
- Keywords
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
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
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";
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
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());
}
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
Keyword | Description |
---|---|
array | Array data type |
bool | Boolean data type |
boolean | Boolean data type (alias of bool ) |
double | Floating point number (alias of float ) |
float | Floating point number |
int | Integer data type |
integer | Integer data type (alias of int ) |
null | Null value |
object | Object data type |
resource | Resource data type |
string | String data type |
Statements and Expressions
Keyword | Description |
---|---|
abstract | Abstract class or method |
and | Logical AND |
as | Alias in foreach loop |
break | Exits a loop or switch statement |
callable | Callable type hint |
case | Case in switch statement |
catch | Catch block in try-catch |
class | Defines a class |
clone | Clones an object |
const | Defines a constant |
continue | Skips the rest of the current loop |
declare | Sets execution directives |
default | Default case in switch statement |
die | Equivalent to exit() |
do | Do-while loop |
echo | Outputs one or more strings |
else | Alternative condition in if-else |
elseif | Else if condition |
empty | Checks if a variable is empty |
enddeclare | Ends declare block |
endfor | Ends for loop |
endforeach | Ends foreach loop |
endif | Ends if block |
endswitch | Ends switch block |
endwhile | Ends while loop |
eval | Evaluates a string as PHP code |
exit | Terminates script execution |
extends | Extends a class |
final | Prevents class/method overriding |
finally | Finally block in try-catch-finally |
for | For loop |
foreach | Foreach loop |
function | Defines a function |
global | Global variable scope |
goto | Jumps to a label |
if | If condition |
implements | Implements an interface |
include | Includes and evaluates a file |
include_once | Includes a file only once |
instanceof | Checks object type |
insteadof | Used with traits |
interface | Defines an interface |
isset | Checks if a variable is set |
list | Assigns variables as if they were an array |
namespace | Defines a namespace |
new | Creates a new object |
or | Logical OR |
print | Outputs a string |
private | Private access modifier |
protected | Protected access modifier |
public | Public access modifier |
require | Includes and evaluates a file |
require_once | Includes a file only once |
return | Returns a value from a function |
static | Declares static properties or methods |
switch | Switch statement |
throw | Throws an exception |
trait | Defines a trait |
try | Try block in try-catch |
unset | Unsets a variable |
use | Imports a namespace or trait |
var | Defines a variable (PHP 4, deprecated in PHP 5) |
while | While loop |
xor | Logical XOR |
yield | Returns a value from a generator |
Magic Constants
Keyword | Description |
---|---|
__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
Keyword | Description |
---|---|
__halt_compiler | Halts the compiler execution |