Welcome to our comprehensive PHP cheat sheet, your ultimate guide to mastering PHP objects and classes! Whether you’re a beginner or an experienced developer, this cheat sheet is packed with essential snippets and quick references to elevate your PHP object-oriented programming skills.
In this guide, we’ll explore the intricacies of objects, classes, constructors, and much more, providing you with a valuable resource for efficient PHP development. Let’s dive in and unlock the power of PHP with our cheat sheet!
PHP is a popular general-purpose scripting language that is especially suited to web development.
For more insights into PHP and WordPress development, check out our posts:
- Preserving Custom Theme Modifications: How to Safely Edit functions.php Without Losing Changes During Theme Updates
- A Basic Intro to WordPress
Basic | Object-Oriented Programming
VARIABLES
Data Types
<?php $integerVar = 42; // Integer $floatVar = 3.14; // Float $stringVar = "PHP is awesome!"; // String $boolVar = true; // Boolean $heredocVar = <<<EOT This is a Heredoc string. It can span multiple lines. EOT; // Heredoc $nullVar = null; // NULL ?>
Constants
<?php define("PI", 3.14); ?>
Comments
<?php // This is a single-line comment /* This is a multi-line comment */ ?>
OPERATORS
Assignment Operators
<?php $a = 5; $b = 10; $a += $b; // Equivalent to $a = $a + $b ?>
Comparison Operators
Equality (==)
<?php $a = 5; $b = "5"; if ($a == $b) { // True if values are equal } else { // False if values are not equal } ?>
Identity (===)
<?php $a = 5; $b = "5"; if ($a === $b) { // True if values and types are equal } else { // False if values or types are not equal } ?>
Inequality (!=)
<?php $a = 10; $b = 5; if ($a != $b) { // True if values are not equal } else { // False if values are equal } ?>
Non-Identity (!==)
<?php $a = 10; $b = "10"; if ($a !== $b) { // True if values or types are not equal } else { // False if values and types are equal } ?>
Greater Than (>)
<?php $a = 10; $b = 5; if ($a > $b) { // True if $a is greater than $b } else { // False if $a is not greater than $b } ?>
Less Than (<)
<?php $a = 5; $b = 10; if ($a < $b) { // True if $a is less than $b } else { // False if $a is not less than $b } ?>
Greater Than or Equal To (>=)
<?php $a = 10; $b = 10; if ($a >= $b) { // True if $a is greater than or equal to $b } else { // False if $a is less than $b } ?>
Less Than or Equal To (<=)
<?php $a = 5; $b = 5; if ($a <= $b) { // True if $a is less than or equal to $b } else { // False if $a is greater than $b } ?>
<?php ?>
AND (&&) Operator
<?php $condition1 = true; $condition2 = false; $andResult = $condition1 && $condition2; // Example of using AND operator ?>
OR (||) Operator
<?php $orResult = $condition1 || $condition2; // Example of using OR operator ?>
NOT (!) operator
<?php $notResult = !$condition1; // Example of using NOT operator ?>
CONTROL FLOW
if
<?php if ($a > $b) { // Code to execute if condition is true } ?>
if else
<?php if ($a > $b) { // Code to execute if condition is true } else { // Code to execute if condition is false } ?>
if elseif
<?php if ($a > $b) { // Code to execute if condition is true } elseif ($a == $b) { // Code to execute if the second condition is true } else { // Code to execute if both conditions are false } ?>
switch
<?php $day = "Monday"; switch ($day) { case "Monday": // Code to execute on Monday break; case "Tuesday": // Code to execute on Tuesday break; // Additional cases as needed default: // Code to execute if no case matches } ?>
for
<?php for ($i = 0; $i < 5; $i++) { // Code to execute in each iteration } ?>
while
<?php while ($a > 0) { // Code to execute while the condition is true $a--; } ?>
do while
<?php do { // Code to execute at least once, then repeat while the condition is true $a--; } while ($a > 0); ?>
foreach
<?php $colors = array("red", "green", "blue"); foreach ($colors as $color) { // Code to execute for each element in the array } ?>
break
<?php for ($i = 0; $i < 10; $i++) { if ($i == 5) { break; // Exit the loop when $i equals 5 } } ?>
continue
<?php for ($i = 0; $i < 10; $i++) { if ($i == 5) { continue; // Skip the rest of the code in the loop when $i equals 5 } // Code here will be skipped when $i equals 5 } ?>
FUNCTIONS
Functions
<?php function greet($name) { echo "Hello, $name!"; // Example of a simple function } greet("John"); ?>
Function Parameters
<?php function add($num1, $num2) { return $num1 + $num2; // Example of a function with parameters } $result = add(3, 7); ?>
Default Parameters
<?php function power($base, $exponent = 2) { return pow($base, $exponent); // Example of a function with default parameters } $square = power(4); // Result: 16 $cube = power(3, 3); // Result: 27 ?>
Named Arguments
<?php function divide($numerator, $denominator) { return $numerator / $denominator; // Example of using named arguments } $quotient = divide(denominator: 2, numerator: 10); ?>
Variable Scopes
<?php $globalVar = 10; // Example of a global variable function exampleFunction() { $localVar = 5; // Example of a local variable within a function } ?>
Type Hints
<?php function addIntegers(int $a, int $b): int { return $a + $b; // Example of type hinting for function parameters and return type } ?>
Strict Typing
<?php declare(strict_types=1); // Enables strict typing function multiply(float $a, float $b): float { return $a * $b; // Example of strict typing for function parameters and return type } ?>
Variadic Functions
<?php function sum(...$numbers) { return array_sum($numbers); // Example of a variadic function } $total = sum(1, 2, 3, 4, 5); // Result: 15 ?>
ARRAYS
Arrays
<?php $numbers = [1, 2, 3, 4, 5]; // Example of a numeric array ?>
Associative Arrays
<?php $person = [ "name" => "John", "age" => 30, "city" => "New York" ]; // Example of an associative array ?>
foreach (for associative arrays)
<?php foreach ($person as $key => $value) { echo "$key: $value\n"; // Example of using foreach with an associative array } ?>
Multidimensional Arrays
<?php $matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; // Example of a multidimensional array ?>
Prepend an Element: array_unshift
<?php array_unshift($numbers, 0); // Example of adding an element to the beginning of an array ?>
Append an Element: array_push
<?php array_push($numbers, 6); // Example of adding an element to the end of an array ?>
Remove the First Element: array_shift
<?php $firstElement = array_shift($numbers); // Example of removing the first element from an array ?>
Remove the Last element: array_pop
<?php $lastElement = array_pop($numbers); // Example of removing the last element from an array ?>
Check If a Key Exists: array_key_exists
<?php $keyExists = array_key_exists("name", $person); // Example of checking if a key exists in an array ?>
Get all Keys: array_keys
<?php $keys = array_keys($person); // Example of getting all keys from an array ?>
Check If a Value Exists: in_array
<?php $valueExists = in_array("John", $person); // Example of checking if a value exists in an array ?>
Merge multiple arrays into one: array_merge
<?php $mergedArray = array_merge($numbers, [6, 7, 8]); // Example of merging multiple arrays into one ?>
Reverse the order of array elements: array_reverse
<?php $reversedArray = array_reverse($numbers); // Example of reversing the order of array elements ?>
Spread Operator
<?php $spreadArray = [...$numbers, 6, 7, 8]; // Example of using the spread operator ?>
SORTING ARRAYS
sort
<?php $numbers = [4, 2, 8, 1]; sort($numbers); // Result: [1, 2, 4, 8] ?>
uasort
<?php $assocArray = ["one" => 1, "three" => 3, "two" => 2]; uasort($assocArray, function($a, $b) { return $a - $b; }); // Result: ["one" => 1, "two" => 2, "three" => 3] ?>
asort
<?php $assocArray = ["one" => 1, "three" => 3, "two" => 2]; asort($assocArray); // Result: ["one" => 1, "two" => 2, "three" => 3] ?>
usort
<?php $numbers = [4, 2, 8, 1]; usort($numbers, function($a, $b) { return $a - $b; }); // Result: [1, 2, 4, 8] ?>
ksort
<?php $assocArray = ["one" => 1, "three" => 3, "two" => 2]; ksort($assocArray); // Result: ["one" => 1, "three" => 3, "two" => 2] ?>
uksort
<?php $assocArray = ["one" => 1, "three" => 3, "two" => 2]; uksort($assocArray, function($a, $b) { return strcmp($a, $b); }); // Result: ["one" => 1, "three" => 3, "two" => 2] ?>
ADVANCED FUNCTIONS
Anonymous Functions
<?php $add = function($a, $b) { return $a + $b; }; $result = $add(3, 5); // Result: 8 ?>
Arrow Functions
<?php $add = fn($a, $b) => $a + $b; $result = $add(3, 5); // Result: 8 ?>
Variable Functions
<?php function greet($name) { echo "Hello, $name!"; } $functionName = "greet"; $functionName("John"); // Output: Hello, John! ?>
ADVANCED ARRAY OPERATIONS
Map Array Elements: array_map
<?php $numbers = [1, 2, 3]; $double = array_map(function($num) { return $num * 2; }, $numbers); // Result: [2, 4, 6] ?>
Filter Array Elements: array_filter
<?php $numbers = [1, 2, 3, 4, 5]; $even = array_filter($numbers, function($num) { return $num % 2 == 0; }); // Result: [2, 4] ?>
Reduce Array Elements: array_reduce
<?php $numbers = [1, 2, 3, 4, 5]; $sum = array_reduce($numbers, function($carry, $num) { return $carry + $num; }, 0); // Result: 15 ?>
FORMS
$_POST
Form Submission
<?php <form method="post" action="process.php"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit" value="Submit"> </form> ?>
PHP Processing
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_POST["username"]; $password = $_POST["password"]; // Process form data } ?>
$_GET
Form Submission
<?php <a href="process.php?category=php&page=variables">PHP Variables</a> ?>
PHP Processing
<?php if ($_SERVER["REQUEST_METHOD"] == "GET") { $category = $_GET["category"]; $page = $_GET["page"]; // Process data from the URL } ?>
$_REQUEST
Form Submission (can handle both POST and GET)
<?php <form method="post" action="process.php"> <input type="text" name="username"> <input type="submit" value="Submit"> </form> ?>
PHP Processing
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_REQUEST["username"]; // Process form data } ?>
$_COOKIE
Setting a Cookie
<?php setcookie("user", "John", time() + 3600, "/"); // Sets a cookie named "user" with the value "John" that expires in 1 hour (3600 seconds). // The cookie is accessible on the entire domain ("/"). ?>
Retrieving a Cookie
<?php $user = $_COOKIE["user"]; ?>
Checking if a Cookie Exists
<?php if (isset($_COOKIE["user"])) { // Cookie exists } else { // Cookie doesn't exist } ?>
Deleting a Cookie
<?php setcookie("user", "", time() - 3600, "/"); // Deletes the "user" cookie by setting its expiration time to a past date. ?>
$_SESSION
Starting a Session
<?php session_start(); // Initiates a new session or resumes the existing session. ?>
Setting Session Variables
<?php $_SESSION["username"] = "John"; ?>
Retrieving Session Variables
<?php $username = $_SESSION["username"]; ?>
Checking if a Session Variable Exists
<?php if (isset($_SESSION["username"])) { // Session variable exists } else { // Session variable doesn't exist } ?>
Unsetting a Session Variable
<?php unset($_SESSION["username"]); ?>
Ending a Session
<?php session_destroy(); ?>
Session Timeout Configuration
<?php // Set session timeout to 30 minutes ini_set('session.gc_maxlifetime', 1800); session_set_cookie_params(1800); ?>
FILE I/O
Open a File – fopen()
<?php $handle = fopen("example.txt", "r"); // Modes: // "r": Read only // "w": Write only (creates or truncates file) // "a": Write only (appends to file) // "r+": Read and write // "w+": Read and write (creates or truncates file) // "a+": Read and write (appends to file) ?>
Check a File Exists – file_exists()
<?php if (file_exists("example.txt")) { // File exists } else { // File doesn't exist } ?>
Read a File: fread() & fgets()
<?php // Reads the entire file into a string. $handle = fopen("example.txt", "r"); $content = fread($handle, filesize("example.txt")); fclose($handle); // Reads a file line by $handle = fopen("example.txt", "r"); while (!feof($handle)) { $line = fgets($handle); // Process each line } fclose($handle); ?>
Read a File into a String – file_get_contents()
<?php $content = file_get_contents("example.txt"); ?>
Download a File – header() & readfile()
<?php header("Content-Disposition: attachment; filename=example.txt"); readfile("example.txt"); ?>
Create Temp File – tempnam()
<?php $tempFile = tempnam(sys_get_temp_dir(), "prefix"); ?>
Copy a File – copy()
<?php copy("source.txt", "destination.txt"); ?>
Delete a File – unlink()
<?php unlink("example.txt"); ?>
Rename a File – rename()
<?php rename("oldname.txt", "newname.txt"); ?>
Read CSV Files – fgetcsv()
<?php $handle = fopen("data.csv", "r"); while (($data = fgetcsv($handle)) !== false) { // Process each CSV row in $data array } fclose($handle); ?>
Objects & Classes
Creating a Class
class MyClass { // Class properties and methods go here }
Creating an Object
$myObject = new MyClass();
$this Keyword
Accessing Class Members
class MyClass { public $property = "Hello"; public function getProperty() { return $this->property; } }
Access Modifiers: public vs. private
Public Access Modifier
class MyClass { public $publicProperty; }
Private Access Modifier
class MyClass { private $privateProperty; }
PHP CONSTRUCTORS & DESTRUCTORS
Constructors
class MyClass { public function __construct() { // Constructor code } }
Destructors
class MyClass { public function __destruct() { // Destructor code } }
PROPERTIES
Typed Properties
class MyClass { public string $name; private int $age; }
Readonly Properties
class MyClass { public readonly string $readOnlyProperty = "Read Only"; }
INHERITANCES
Inheritances
class ParentClass { // Parent class code } class ChildClass extends ParentClass { // Child class code }
Calling the Parent Constructor
class ChildClass extends ParentClass { public function __construct() { parent::__construct(); // Child class constructor code } }
Overriding Methods
class ParentClass { public function myMethod() { echo "Parent method"; } } class ChildClass extends ParentClass { public function myMethod() { echo "Child method"; } }
The protected Keyword
class ParentClass { protected $protectedProperty; }
POLYMORPHISM
Polymorphism
interface Shape { public function calculateArea(); } class Circle implements Shape { // Circle implementation } class Square implements Shape { // Square implementation }
TRAITS
Traits
trait MyTrait { // Trait code } class MyClass { use MyTrait; }
STATIC METHODS & PROPERTIES
Static Methods & Properties
class MyClass { public static $staticProperty; public static function staticMethod() { // Static method code } }
Class Constants
class MyClass { const MY_CONSTANT = "Constant Value"; }
Late Static Binding
class ParentClass { public static function whoAmI() { echo "I am the Parent!"; } } class ChildClass extends ParentClass { public static function whoAmI() { parent::whoAmI(); echo "I am the Child!"; } }
MAGIC METHODS
PHP Magic Methods
class MyClass { // Magic methods go here } $instance = new MyClass(); <code>class MyClass { // Magic methods go here } $instance = new MyClass();</code>
__toString()
class MyClass { public function __toString() { return "This is my class!"; } }
__call()
class MyClass { public function __call($name, $arguments) { echo "Calling method $name with arguments: " . implode(', ', $arguments); } }
__callStatic()
class MyClass { public static function __callStatic($name, $arguments) { echo "Calling static method $name with arguments: " . implode(', ', $arguments); } }
__invoke()
class MyClass { public function __invoke() { echo "Object is called as a function!"; } }
__clone()
class MyClass { public function __clone() { echo "Object is cloned!"; } }
WORKING WITH OBJECTS
Comparing Objects
$obj1 = new MyClass(); $obj2 = new MyClass(); if ($obj1 == $obj2) { // True if objects are equal } else { // False if objects are not equal }
Cloning Objects
$cloneObj = clone $originalObj;
Anonymous Classes
$anonObj = new class { // Class code };
NAMESPACES
Namespaces
namespace MyNamespace; class MyClass { // Class code }
AUTOLOADING
Autoloading Class Files
spl_autoload_register(function ($class) { include 'classes/' . $class . '.class.php'; });
Autoloading with Composer
spl_autoload_register(function ($class) { include 'classes/' . $class . '.class.php'; });
EXCEPTION HANDLING
try…catch
try { // Code that may throw an exception } catch (Exception $e) { // Handle the exception }
try…catch…finally
try { // Code that may throw an exception } catch (Exception $e) { // Handle the exception } finally { // Code that always runs }
throw an Exception
throw new Exception("Something went wrong!");
Set Exception Handlers
set_exception_handler(function ($exception) { // Handle uncaught exceptions });
Congratulations on completing our PHP Objects & Classes cheat sheet! We hope this resource has been a valuable companion in your journey to mastering PHP OOP. Bookmark this cheat sheet for quick reference and make your coding tasks more efficient.
If you’re hungry for more knowledge, don’t forget to explore our other insightful posts:
- Preserving Custom Theme Modifications: How to Safely Edit functions.php Without Losing Changes During Theme Updates
- A Basic Intro to WordPress
Stay tuned for more PHP and WordPress tips, and happy coding!