2021-01-05 21:25:08 +08:00
---
title: PHP
date: 2021-01-04 15:23:28
2021-12-15 10:48:31 +08:00
background: bg-[#7477a9 ]
2021-01-05 21:25:08 +08:00
tags:
2024-05-22 03:37:57 -07:00
- web
2021-01-05 21:25:08 +08:00
categories:
2024-05-22 03:37:57 -07:00
- Programming
2021-01-05 21:25:08 +08:00
intro: |
2024-05-22 03:37:57 -07:00
This [PHP ](https://www.php.net/manual/en/ ) cheat sheet provides a reference for quickly looking up the correct syntax for the code you use most frequently.
2023-03-06 16:19:19 +08:00
plugins:
2024-05-22 03:37:57 -07:00
- copyCode
2025-01-05 14:30:48 +02:00
- runCode
2021-01-05 21:25:08 +08:00
---
2024-05-22 03:37:57 -07:00
## Getting Started
2021-01-05 21:25:08 +08:00
### hello.php
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
``` php
< ? php // begin with a PHP open tag.
echo " Hello World \n " ;
2023-06-15 10:44:51 +08:00
print ( " Hello cheatsheets.zip " );
2021-01-05 21:25:08 +08:00
?>
```
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
PHP run command
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
```shell script
$ php hello.php
` ``
### Variables
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$boolean1 = true;
$boolean2 = True;
$int = 12;
$float = 3.1415926;
unset($float); // Delete variable
$str1 = "How are you?";
$str2 = 'Fine, thanks';
` ``
2024-05-22 03:37:57 -07:00
See: [Types](#php-types)
2021-01-05 21:25:08 +08:00
### Strings
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
2023-06-15 10:44:51 +08:00
$url = "cheatsheets.zip";
2021-01-05 21:25:08 +08:00
echo "I'm learning PHP at $url";
// Concatenate strings
echo "I'm learning PHP at " . $url;
$hello = "Hello, ";
$hello .= "World!";
echo $hello; # => Hello, World!
` ``
2024-05-22 03:37:57 -07:00
See: [Strings](#php-strings)
2021-01-05 21:25:08 +08:00
### Arrays
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$num = [1, 3, 5, 7, 9];
$num[5] = 11;
unset($num[2]); // Delete variable
print_r($num); # => 1 3 7 9 11
echo count($num); # => 5
` ``
2024-05-22 03:37:57 -07:00
See: [Arrays](#php-arrays)
2021-01-05 21:25:08 +08:00
### Operators
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$x = 1;
$y = 2;
$sum = $x + $y;
echo $sum; # => 3
` ``
2024-05-22 03:37:57 -07:00
See: [Operators](#php-operators)
2021-01-05 21:25:08 +08:00
### Include {.row-span-3}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
#### vars.php
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
<?php // begin with a PHP open tag.
$fruit = 'apple';
echo "I was imported";
return 'Anything you like.';
?>
` ``
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
#### test.php
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
<?php
include 'vars.php';
echo $fruit . "\n"; # => apple
/* Same as include,
cause an error if cannot be included*/
require 'vars.php';
2021-01-06 14:33:07 +08:00
// Also works
include('vars.php');
require('vars.php');
2021-01-05 21:25:08 +08:00
// Include through HTTP
include 'http://x.com/file.php';
// Include and the return statement
$result = include 'vars.php';
echo $result; # => Anything you like.
?>
` ``
### Functions
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
function add($num1, $num2 = 1) {
return $num1 + $num2;
}
echo add(10); # => 11
echo add(10, 5); # => 15
` ``
2024-05-22 03:37:57 -07:00
See: [Functions](#php-functions)
2021-01-05 21:25:08 +08:00
2024-05-22 03:37:57 -07:00
### Comments
2021-01-05 21:25:08 +08:00
` ``php
# This is a one line shell-style comment
// This is a one line c++ style comment
/* This is a multi line comment
yet another line of comment */
` ``
### Constants
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
2021-01-05 22:45:25 +00:00
const MY_CONST = "hello";
2021-01-05 21:25:08 +08:00
echo MY_CONST; # => hello
# => MY_CONST is: hello
2024-05-22 03:37:57 -07:00
echo 'MY_CONST is: ' . MY_CONST;
2021-01-05 21:25:08 +08:00
` ``
### Classes
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
class Student {
public function __construct($name) {
$this->name = $name;
}
}
$alex = new Student("Alex");
` ``
2024-05-22 03:37:57 -07:00
See: [Classes](#php-classes)
2021-01-05 21:25:08 +08:00
2024-05-22 03:37:57 -07:00
## PHP Types
2021-01-05 21:25:08 +08:00
### Boolean {.row-span-2}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$boolean1 = true;
$boolean2 = TRUE;
$boolean3 = false;
$boolean4 = FALSE;
$boolean5 = (boolean) 1; # => true
$boolean6 = (boolean) 0; # => false
` ``
2024-05-22 03:37:57 -07:00
Boolean are case-insensitive
2021-01-05 21:25:08 +08:00
### Integer {.row-span-2}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$int1 = 28; # => 28
$int2 = -32; # => -32
$int3 = 012; # => 10 (octal)
$int4 = 0x0F; # => 15 (hex)
$int5 = 0b101; # => 5 (binary)
# => 2000100000 (decimal, PHP 7.4.0)
$int6 = 2_000_100_000;
` ``
2024-05-22 03:37:57 -07:00
See also: [Integers](https://www.php.net/manual/en/language.types.integer.php)
2021-01-05 21:25:08 +08:00
### Strings
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
echo 'this is a simple string';
` ``
2024-05-22 03:37:57 -07:00
2021-12-19 15:22:40 +08:00
See: [Strings](#php-strings)
2021-01-05 21:25:08 +08:00
### Arrays
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$arr = array("hello", "world", "!");
` ``
2024-05-22 03:37:57 -07:00
See: [Arrays](#php-arrays)
2021-01-05 21:25:08 +08:00
### Float (Double)
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$float1 = 1.234;
$float2 = 1.2e7;
$float3 = 7E-10;
$float4 = 1_234.567; // as of PHP 7.4.0
var_dump($float4); // float(1234.567)
$float5 = 1 + "10.5"; # => 11.5
$float6 = 1 + "-1.3e3"; # => -1299
` ``
### Null
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$a = null;
$b = 'Hello php!';
echo $a ?? 'a is unset'; # => a is unset
echo $b ?? 'b is unset'; # => Hello php
$a = array();
$a == null # => true
$a === null # => false
is_null($a) # => false
` ``
### Iterables
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
function bar(): iterable {
return [1, 2, 3];
}
function gen(): iterable {
yield 1;
yield 2;
yield 3;
}
foreach (bar() as $value) {
echo $value; # => 123
2024-05-22 03:37:57 -07:00
}
2021-01-05 21:25:08 +08:00
` ``
2024-05-22 03:37:57 -07:00
## PHP Strings
2021-01-05 21:25:08 +08:00
### String
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
# => '$String'
$sgl_quotes = '$String';
# => 'This is a $String.'
$dbl_quotes = "This is a $sgl_quotes.";
# => a tab character.
$escaped = "a \t tab character.";
# => a slash and a t: \t
$unescaped = 'a slash and a t: \t';
` ``
### Multi-line
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$str = "foo";
// Uninterpolated multi-liners
$nowdoc = <<<'END'
Multi line string
$str
END;
// Will do string interpolation
$heredoc = <<<END
Multi line
$str
END;
` ``
### Manipulation
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$s = "Hello Phper";
echo strlen($s); # => 11
echo substr($s, 0, 3); # => Hel
echo substr($s, 1); # => ello Phper
echo substr($s, -4, 3);# => hpe
echo strtoupper($s); # => HELLO PHPER
echo strtolower($s); # => hello phper
echo strpos($s, "l"); # => 2
var_dump(strpos($s, "L")); # => false
` ``
2024-05-22 03:37:57 -07:00
See: [String Functions](https://www.php.net/manual/en/ref.strings.php)
2021-01-05 21:25:08 +08:00
2024-05-22 03:37:57 -07:00
## PHP Arrays
2021-01-05 21:25:08 +08:00
### Defining {.row-span-2}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$a1 = ["hello", "world", "!"]
$a2 = array("hello", "world", "!");
$a3 = explode(",", "apple,pear,peach");
` ``
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
#### Mixed int and string keys
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
` ``
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
#### Short array syntax
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$array = [
"foo" => "bar",
"bar" => "foo",
];
` ``
### Multi array
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
2024-05-22 03:37:57 -07:00
$multiArray = [
2021-01-05 21:25:08 +08:00
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
print_r($multiArray[0][0]) # => 1
print_r($multiArray[0][1]) # => 2
print_r($multiArray[0][2]) # => 3
` ``
### Multi type {.row-span-2}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dim" => array(
"a" => "foo"
)
)
);
# => string(3) "bar"
var_dump($array["foo"]);
# => int(24)
2024-05-22 03:37:57 -07:00
var_dump($array[42]);
2021-01-05 21:25:08 +08:00
# => string(3) "foo"
var_dump($array["multi"]["dim"]["a"]);
` ``
### manipulation
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // Append
$arr["x"] = 42; // Add with key
sort($arr); // Sort
unset($arr[5]); // Remove
unset($arr); // Remove all
` ``
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
See: [Array Functions](https://www.php.net/manual/en/ref.array.php)
### Indexing iteration
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$array = array('a', 'b', 'c');
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "i:{$i}, v:{$array[$i]}\n";
}
` ``
### Value iteration
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$colors = array('red', 'blue', 'green');
foreach ($colors as $color) {
echo "Do you like $color?\n";
}
` ``
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
### Key iteration
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$arr = ["foo" => "bar", "bar" => "foo"];
foreach ( $arr as $key => $value )
{
echo "key: " . $key . "\n";
echo "val: {$arr[$key]}\n";
}
` ``
### Concatenate arrays
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$a = [1, 2];
$b = [3, 4];
// PHP 7.4 later
# => [1, 2, 3, 4]
$result = [...$a, ...$b];
` ``
### Into functions
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$array = [1, 2];
function foo(int $a, int $b) {
echo $a; # => 1
echo $b; # => 2
}
foo(...$array);
` ``
2021-01-06 14:33:07 +08:00
### Splat Operator
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
function foo($first, ...$other) {
var_dump($first); # => a
var_dump($other); # => ['b', 'c']
}
foo('a', 'b', 'c' /*, ...*/ );
// or
function foo($first, string ...$other){}
` ``
2024-05-22 03:37:57 -07:00
## PHP Operators {.cols-4}
2021-01-05 21:25:08 +08:00
### Arithmetic
2024-05-22 03:37:57 -07:00
2021-09-14 13:03:55 +08:00
| - | - |
2024-05-22 03:37:57 -07:00
| ---- | -------------- |
2021-01-05 21:25:08 +08:00
| ` +` | Addition |
| ` -` | Subtraction |
| ` *` | Multiplication |
| ` /` | Division |
| ` %` | Modulo |
| ` **` | Exponentiation |
### Assignment
2024-05-22 03:37:57 -07:00
2021-09-14 13:03:55 +08:00
| - | - |
2024-05-22 03:37:57 -07:00
| -------- | ------------------- |
2021-01-05 21:25:08 +08:00
| ` a += b` | Same as ` a = a + b` |
| ` a -= b` | Same as ` a = a – b` |
| ` a * = b` | Same as `a = a * b` |
| ` a /= b` | Same as ` a = a / b` |
| ` a %= b` | Same as ` a = a % b` |
### Comparison {.row-span-2}
2024-05-22 03:37:57 -07:00
2021-09-14 13:03:55 +08:00
| - | - |
2024-05-22 03:37:57 -07:00
| ----- | ---------------------------- |
2021-01-05 21:25:08 +08:00
| ` ==` | Equal |
| ` ===` | Identical |
| ` !=` | Not equal |
| ` <>` | Not equal |
| ` !==` | Not identical |
| ` <` | Less than |
| ` >` | Greater than |
| ` <=` | Less than or equal |
| ` >=` | Greater than or equal |
| ` <=>` | Less than/equal/greater than |
### Logical
2024-05-22 03:37:57 -07:00
2021-09-14 13:03:55 +08:00
| - | - |
2024-05-22 03:37:57 -07:00
| ----- | ------------ | --- | --- |
2021-09-14 13:03:55 +08:00
| ` and` | And |
| ` or` | Or |
| ` xor` | Exclusive or |
| ` !` | Not |
| ` &&` | And |
2024-05-22 03:37:57 -07:00
| ` | | ` | Or |
2021-01-05 21:25:08 +08:00
### Arithmetic {.col-span-2}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
// Arithmetic
$sum = 1 + 1; // 2
$difference = 2 - 1; // 1
$product = 2 * 2; // 4
$quotient = 2 / 1; // 2
// Shorthand arithmetic
$num = 0;
$num += 1; // Increment $num by 1
echo $num++; // Prints 1 (increments after evaluation)
echo ++$num; // Prints 3 (increments before evaluation)
$num /= $float; // Divide and assign the quotient to $num
` ``
### Bitwise
2024-05-22 03:37:57 -07:00
2021-09-14 13:03:55 +08:00
| - | - |
2024-05-22 03:37:57 -07:00
| ---- | ------------------ | ----------------- |
2021-01-05 21:25:08 +08:00
| ` &` | And |
2024-05-22 03:37:57 -07:00
| ` | ` | Or (inclusive or) |
2021-01-05 21:25:08 +08:00
| ` ^` | Xor (exclusive or) |
| ` ~` | Not |
| ` <<` | Shift left |
| ` >>` | Shift right |
2024-05-22 03:37:57 -07:00
## PHP Conditionals
2021-01-05 21:25:08 +08:00
### If elseif else
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$a = 10;
$b = 20;
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
` ``
### Switch
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$x = 0;
switch ($x) {
case '0':
print "it's zero";
2024-05-22 03:37:57 -07:00
break;
2021-01-05 21:25:08 +08:00
case 'two':
case 'three':
// do something
break;
default:
// do something
}
` ``
### Ternary operator
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
# => Does
print (false ? 'Not' : 'Does');
$x = false;
# => Does
print($x ?: 'Does');
$a = null;
$b = 'Does print';
2023-02-11 22:41:24 +03:30
# => a is unset
2021-01-05 21:25:08 +08:00
echo $a ?? 'a is unset';
# => print
echo $b ?? 'b is unset';
` ``
2021-01-06 14:33:07 +08:00
### Match
2024-05-22 03:37:57 -07:00
2021-01-06 14:33:07 +08:00
` ``php
$statusCode = 500;
$message = match($statusCode) {
200, 300 => null,
400 => 'not found',
500 => 'server error',
default => 'known status code',
};
echo $message; # => server error
` ``
2024-05-22 03:37:57 -07:00
See: [Match](https://www.php.net/manual/en/control-structures.match.php)
2021-01-06 14:33:07 +08:00
### Match expressions
2024-05-22 03:37:57 -07:00
2021-01-06 14:33:07 +08:00
` ``php
$age = 23;
$result = match (true) {
$age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
echo $result; # => young adult
` ``
2021-01-05 21:25:08 +08:00
2024-05-22 03:37:57 -07:00
## PHP Loops
2021-01-05 21:25:08 +08:00
### while
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$i = 1;
# => 12345
while ($i <= 5) {
echo $i++;
}
` ``
### do while
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$i = 1;
# => 12345
do {
echo $i++;
} while ($i <= 5);
` ``
### for i
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
# => 12345
for ($i = 1; $i <= 5; $i++) {
echo $i;
}
` ``
### break
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
# => 123
for ($i = 1; $i <= 5; $i++) {
if ($i === 4) {
break;
}
echo $i;
}
` ``
### continue
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
# => 1235
for ($i = 1; $i <= 5; $i++) {
if ($i === 4) {
continue;
}
echo $i;
}
` ``
### foreach
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$a = ['foo' => 1, 'bar' => 2];
# => 12
foreach ($a as $k) {
echo $k;
}
` ``
2024-05-22 03:37:57 -07:00
See: [Array iteration](#php-value-iteration)
2021-01-05 21:25:08 +08:00
2024-05-22 03:37:57 -07:00
## PHP Functions
2021-01-05 21:25:08 +08:00
### Returning values
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
function square($x)
{
return $x * $x;
}
2021-01-06 14:33:07 +08:00
2021-01-05 21:25:08 +08:00
echo square(4); # => 16
` ``
2021-01-06 14:33:07 +08:00
### Return types
2024-05-22 03:37:57 -07:00
2021-01-06 14:33:07 +08:00
` ``php
// Basic return type declaration
function sum($a, $b): float {/*...*/}
function get_item(): string {/*...*/}
class C {}
// Returning an object
function getC(): C { return new C; }
` ``
### Nullable return types
2024-05-22 03:37:57 -07:00
2021-01-06 14:33:07 +08:00
` ``php
// Available in PHP 7.1
function nullOrString(int $v) : ?string
{
return $v % 2 ? "odd" : null;
}
echo nullOrString(3); # => odd
var_dump(nullOrString(4)); # => NULL
` ``
2024-05-22 03:37:57 -07:00
2021-01-06 14:33:07 +08:00
See: [Nullable types](https://www.php.net/manual/en/migration71.new-features.php)
2021-01-05 21:25:08 +08:00
2021-01-06 14:33:07 +08:00
### Void functions
2024-05-22 03:37:57 -07:00
2021-01-06 14:33:07 +08:00
` ``php
// Available in PHP 7.1
function voidFunction(): void
{
echo 'Hello';
return;
}
2021-01-05 21:25:08 +08:00
2021-01-06 14:33:07 +08:00
voidFunction(); # => Hello
` ``
2021-01-05 21:25:08 +08:00
### Variable functions
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
function bar($arg = '')
{
echo "In bar(); arg: '$arg'.\n";
}
$func = 'bar';
$func('test'); # => In bar(); arg: test
` ``
### Anonymous functions
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
2021-01-06 14:33:07 +08:00
$greet('World'); # => Hello World
$greet('PHP'); # => Hello PHP
2021-01-05 21:25:08 +08:00
` ``
2021-01-06 14:33:07 +08:00
### Recursive functions
2024-05-22 03:37:57 -07:00
2021-01-06 14:33:07 +08:00
` ``php
function recursion($x)
{
if ($x < 5) {
echo "$x";
recursion($x + 1);
}
}
recursion(1); # => 1234
` ``
2021-01-05 21:25:08 +08:00
### Default parameters
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
function coffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
# => Making a cup of cappuccino.
echo coffee();
# => Making a cup of .
echo coffee(null);
# => Making a cup of espresso.
echo coffee("espresso");
` ``
### Arrow Functions
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
$y = 1;
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
$fn1 = fn($x) => $x + $y;
// equivalent to using $y by value:
$fn2 = function ($x) use ($y) {
return $x + $y;
};
echo $fn1(5); # => 6
echo $fn2(5); # => 6
` ``
2024-05-22 03:37:57 -07:00
## PHP Classes
2021-01-05 21:25:08 +08:00
### Constructor
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
class Student {
public function __construct($name) {
$this->name = $name;
}
public function print() {
echo "Name: " . $this->name;
}
}
$alex = new Student("Alex");
$alex->print(); # => Name: Alex
` ``
### Inheritance
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
class ExtendClass extends SimpleClass
{
// Redefine the parent method
function displayVar()
{
echo "Extending class\n";
parent::displayVar();
}
}
$extended = new ExtendClass();
$extended->displayVar();
` ``
### Classes variables {.row-span-2}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
class MyClass
{
const MY_CONST = 'value';
static $staticVar = 'static';
// Visibility
public static $var1 = 'pubs';
// Class only
private static $var2 = 'pris';
// The class and subclasses
protected static $var3 = 'pros';
// The class and subclasses
protected $var6 = 'pro';
// The class only
2024-05-22 03:37:57 -07:00
private $var7 = 'pri';
2021-01-05 21:25:08 +08:00
}
` ``
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
Access statically
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
echo MyClass::MY_CONST; # => value
echo MyClass::$staticVar; # => static
` ``
### Magic Methods
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
class MyClass
{
// Object is treated as a String
public function __toString()
{
return $property;
}
// opposite to __construct()
public function __destruct()
{
print "Destroying";
}
}
` ``
### Interface
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
2024-05-22 03:37:57 -07:00
interface Foo
2021-01-05 21:25:08 +08:00
{
public function doSomething();
}
interface Bar
{
public function doSomethingElse();
}
2024-05-22 03:37:57 -07:00
class Cls implements Foo, Bar
2021-01-05 21:25:08 +08:00
{
public function doSomething() {}
public function doSomethingElse() {}
}
` ``
2025-06-18 19:36:27 +02:00
## PHP Trait
### Trait declaration & Use case {.col-span-3}
` ``php
// Declare Trait allows reuse of code
// across multiple classes for common characteristics or use cases
<?php
trait Logger {
public function log($message) {
$date = new DateTime();
echo "| ". $date->format('Y-m-d H:i:s') . " | " . $message;
}
}
// Use case :
// Call trait with "use <trait name> in Class"
class User {
use Logger;
public function createUser() {
// User creation logic
$this->log("User created.");
}
}
class Product {
use Logger;
public function createProduct() {
// Product creation logic
$this->log("Product created.");
}
}
$user = new User();
$user->createUser(); // Output ex: | 2025-06-18 14:06:09 | User created.
$product = new Product();
$product->createProduct(); // Output ex: | 2025-06-18 14:06:09 | Product created.
` ``
2025-06-18 19:43:23 +02:00
## PHP Enums (PHP 8.1)
### Enum Declaration & Use case {.col-span-3}
` ``php
<?php
// enum is a data type that allows you to define a set of named constants,
// representing a fixed group of related values
enum Status {
case Pending;
case Approved;
case Rejected;
}
// Use case
function getStatusMessage(Status $status): string {
return match($status) {
Status::Pending => "Waiting for approval.",
Status::Approved => "Your request has been approved.",
Status::Rejected => "Your request has been rejected.",
};
}
$currentStatus = Status::Approved;
echo getStatusMessage($currentStatus); // Output : Your request has been approved.
` ``
2025-06-18 20:07:03 +02:00
## PHP Date & Time Handling
2025-06-18 19:58:56 +02:00
### Current date and time
` ``php
// DateTime in PHP handles both date and time
<?php
$now = new DateTime();
echo $now->format('Y-m-d H:i:s.u');
// Output ex: 2024-04-27 14:35:22.123456
` ``
### Creating specific date/time objects
` ``php
<?php
// Create a date object
$d = new DateTime('2024-04-27');
echo $d->format('Y-m-d');
// Output : 2024-04-27
// Create a time object
$t = new DateTime('15:30:45');
echo $t->format('H:i:s');
// Output : 15:30:45
// Create a datetime object
$dt = new DateTime('2024-04-27 15:30:45');
echo $dt->format('Y-m-d H:i:s');
// Output : 2024-04-27 15:30:45
` ``
### Converting between date formats
` ``php
<?php
// Convert a string to a DateTime object
$date_str = "2024-04-27 14:00";
$dt_obj = new DateTime($date_str);
echo $dt_obj->format('Y-m-d H:i:s');
// Output : 2024-04-27 14:00:0027
// Convert a DateTime object to a string
$formatted_str = $dt_obj->format('d/m/Y H:i');
echo $formatted_str;
// Output : 27/04/2024 14:00
` ``
### Timestamps and Unix time {.col-span-2}
` ``php
<?php
// Get current timestamp
$timestamp = time();
echo $timestamp;
// Output ex: 1750253583
// Convert timestamp back to DateTime
$dt_from_timestamp = (new DateTime())->setTimestamp($timestamp);
echo $dt_from_timestamp->format('Y-m-d H:i:s');
// Output ex : 2025-06-18 13:33:03
` ``
### Date difference and timedelta {.col-span-1}
` ``php
<?php
$date1 = new DateTime('2024-04-27');
$date2 = new DateTime('2024-05-01');
$interval = $date1->diff($date2);
echo $interval->days;
// Output : 4
// Using DateInterval for date arithmetic
$new_date = clone $date1;
$new_date->add(new DateInterval('P10D'));
echo $new_date->format('Y-m-d');
// Output : 2024-05-07
` ``
2025-06-18 19:43:23 +02:00
2024-05-22 03:37:57 -07:00
## Miscellaneous
2021-01-05 21:25:08 +08:00
### Basic error handling
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
try {
// Do something
} catch (Exception $e) {
// Handle exception
} finally {
echo "Always print!";
}
` ``
### Exception in PHP 8.0 {.col-span-2}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php {.wrap}
$nullableValue = null;
try {
$value = $nullableValue ?? throw new InvalidArgumentException();
} catch (InvalidArgumentException) { // Variable is optional
// Handle my exception
echo "print me!";
}
` ``
### Custom exception {.row-span-2}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
class MyException extends Exception {
// do something
}
` ``
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
Usage
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
try {
$condition = true;
if ($condition) {
throw new MyException('bala');
}
} catch (MyException $e) {
// Handle my exception
}
` ``
### Nullsafe Operator {.row-span-2}
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
// As of PHP 8.0.0, this line:
$result = $repo?->getUser(5)?->name;
// Equivalent to the following code:
if (is_null($repo)) {
$result = null;
} else {
$user = $repository->getUser(5);
if (is_null($user)) {
$result = null;
} else {
$result = $user->name;
}
}
` ``
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
See also: [Nullsafe Operator](https://wiki.php.net/rfc/nullsafe_operator)
### Regular expressions
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
` ``php
2024-07-17 11:36:52 +08:00
$str = "Visit cheatsheets.zip";
echo preg_match("/ch/i", $str); # => 1
2021-01-05 21:25:08 +08:00
` ``
2024-05-22 03:37:57 -07:00
2021-01-05 21:25:08 +08:00
See: [Regex in PHP](/regex#regex-in-php)
### fopen() mode
| - | - |
2024-05-22 03:37:57 -07:00
| ---- | ------------------------ |
2021-01-05 21:25:08 +08:00
| ` r` | Read |
| ` r+` | Read and write, prepend |
| ` w` | Write, truncate |
| ` w+` | Read and write, truncate |
| ` a` | Write, append |
| ` a+` | Read and write, append |
2025-06-18 20:07:03 +02:00
### Super Global Variables {.col-span-2}
| Variable | Description |
|--------------|:-------------------------------------------------------------|
| ` $_SERVER` | Holds information about headers, paths, and script locations |
| ` $_GET` | Contains data sent via URL parameters (query string) |
| ` $_POST` | Contains data sent via HTTP POST method |
| ` $_FILES` | Contains information about uploaded files |
| ` $_COOKIE` | Contains cookie data |
| ` $_SESSION` | Stores session variables |
| ` $_REQUEST` | Contains data from ` $_GET`, ` $_POST`, and ` $_COOKIE` |
| ` $_ENV` | Contains environment variables |
| ` $GLOBALS` | References all global variables available in the script |
{.left-text}
Super Global Variables are built-in variables always available in all scopes.
2021-01-06 14:33:07 +08:00
### Runtime defined Constants
2024-05-22 03:37:57 -07:00
2021-01-06 14:33:07 +08:00
` ``php
define("CURRENT_DATE", date('Y-m-d'));
// One possible representation
echo CURRENT_DATE; # => 2021-01-05
# => CURRENT_DATE is: 2021-01-05
2024-05-22 03:37:57 -07:00
echo 'CURRENT_DATE is: ' . CURRENT_DATE;
2021-01-06 14:33:07 +08:00
` ``
2024-05-22 03:37:57 -07:00
## Also see
2021-01-05 21:25:08 +08:00
2021-01-06 14:33:07 +08:00
- [PHP Docs ](https://www.php.net/manual/en/index.php )
2021-01-05 21:25:08 +08:00
- [Learn X in Y minutes ](https://learnxinyminutes.com/docs/php/ )