Skip to main content

The PHP Programming Language

1. Introduction to PHP

1.1 What is PHP?

  • PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development.
  • It is embedded within HTML and executed on the server, generating HTML that is sent to the client.
  • How it runs: The PHP interpreter processes .php files, executing code between <?php ... ?> tags.
  • Typical use cases: Dynamic websites, web applications, REST APIs, command-line scripts, and content management systems (e.g., WordPress).

1.2 Basic Syntax

  • PHP files start with <?php and end with ?> (closing tag optional in pure PHP files).
  • Statements end with a semicolon ;.
  • Comments: // Single-line, # Also single-line, /* Multi-line */.

1.3 Variables & Data Types

  • Variables start with $ followed by a name (case-sensitive).
  • Loose typing: Type is determined by context.
  • Main data types:
    • Scalar: string, int, float, bool
    • Compound: array, object, callable, iterable
    • Special: null, resource

Code Snippet:

<?php
$name = "Alice"; // String
$age = 30; // Integer
$price = 19.99; // Float
$isActive = true; // Boolean
$items = [1, 2, 3]; // Array
$nullVar = null; // Null

// Variable interpolation in strings
echo "Hello, $name! You are $age years old.";
?>

Common Pitfalls:

  • Variables must be defined before use (no default value).
  • Strings with variables require double quotes or concatenation.

2. Control Structures

2.1 Conditionals

  • if/elseif/else
  • switch statement

Code Snippet:

// if/elseif/else
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B"; // This will execute
} else {
echo "Grade: C";
}

// switch
$day = "Mon";
switch ($day) {
case "Mon":
echo "Start of work week";
break;
case "Fri":
echo "Weekend is near";
break;
default:
echo "Regular day";
}

2.2 Loops

  • while, do-while, for, foreach

Code Snippet:

// while
$i = 0;
while ($i < 3) {
echo $i++; // 0, 1, 2
}

// for
for ($j = 0; $j < 3; $j++) {
echo $j; // 0, 1, 2
}

// foreach (arrays)
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color; // red, green, blue
}

// foreach with keys
$person = ["name" => "John", "age" => 25];
foreach ($person as $key => $value) {
echo "$key: $value"; // name: John, age: 25
}

Best Practice: Use foreach for arrays; avoid modifying array pointers manually.


3. Functions in PHP

3.1 Declaring Functions

  • Use function keyword.
  • Parameters can have default values.
  • Return values with return.

Code Snippet:

function greet($name = "Guest") {
return "Hello, $name!";
}
echo greet("Alice"); // Hello, Alice!
echo greet(); // Hello, Guest!

// Type declarations (PHP 7+)
function add(int $a, int $b): int {
return $a + $b;
}

3.2 Variable Scope

  • Variables inside functions are local.
  • Access global variables with global keyword or $GLOBALS (avoid when possible).
  • Static variables persist between function calls.

Code Snippet:

$globalVar = "I'm global";

function testScope() {
global $globalVar; // Not recommended
$localVar = "I'm local";
static $count = 0;
$count++;
echo $count;
}

3.3 Anonymous Functions & Closures

  • Functions without a name, assigned to variables.

Code Snippet:

$add = function($a, $b) {
return $a + $b;
};
echo $add(2, 3); // 5

// Closure with 'use' to inherit variables
$multiplier = 2;
$double = function($num) use ($multiplier) {
return $num * $multiplier;
};

Common Pitfall: Overusing global variables leads to tightly coupled, hard-to-debug code.


4. Working with Arrays

4.1 Array Types

  • Indexed arrays: Numeric keys starting from 0.
  • Associative arrays: String keys (key-value pairs).
  • Multidimensional arrays: Arrays containing other arrays.

Code Snippet:

// Indexed
$fruits = ["Apple", "Banana", "Cherry"];

// Associative
$user = [
"name" => "John",
"email" => "john@example.com"
];

// Multidimensional
$matrix = [
[1, 2, 3],
[4, 5, 6]
];
echo $matrix[1][2]; // 6

4.2 Array Functions

  • PHP has 80+ built-in array functions.

Code Snippet:

$numbers = [1, 2, 3, 4];

// Adding/removing
array_push($numbers, 5); // End
array_pop($numbers); // Remove last
array_unshift($numbers, 0); // Beginning
array_shift($numbers); // Remove first

// Iteration
array_map(function($n) {
return $n * 2;
}, $numbers);

// Filtering
$evens = array_filter($numbers, function($n) {
return $n % 2 === 0;
});

// Searching
$key = array_search(3, $numbers); // Returns key (2)

// Merging
$merged = array_merge([1, 2], [3, 4]);

Best Practice: Use array functions instead of manual loops for readability and performance.


5. Object-Oriented Programming (OOP)

5.1 Classes & Objects

  • Class: Blueprint for objects.
  • Properties: Variables inside a class.
  • Methods: Functions inside a class.

Code Snippet:

class Car {
// Properties
public $brand;
private $mileage = 0;

// Constructor
public function __construct($brand) {
$this->brand = $brand;
}

// Method
public function drive($distance) {
$this->mileage += $distance;
echo "Driving $distance miles";
}

// Getter
public function getMileage(): int {
return $this->mileage;
}
}

$myCar = new Car("Toyota");
$myCar->drive(100);
echo $myCar->getMileage(); // 100

5.2 Inheritance

  • Use extends keyword.

Code Snippet:

class Vehicle {
protected $wheels = 4;

public function honk() {
echo "Beep!";
}
}

class Motorcycle extends Vehicle {
public function __construct() {
$this->wheels = 2;
}
}

5.3 Interfaces & Abstract Classes

  • Interface: Defines a contract (methods without implementation).
  • Abstract class: Cannot be instantiated; may contain implementation.

Code Snippet:

interface Logger {
public function log($message);
}

abstract class Shape {
abstract public function area();

public function description() {
return "I'm a shape";
}
}

class Circle extends Shape implements Logger {
public function area() { /* ... */ }
public function log($message) { /* ... */ }
}

5.4 Traits

  • Mechanism for code reuse in single inheritance languages.

Code Snippet:

trait Loggable {
public function log($msg) {
echo "Logging: $msg";
}
}

class User {
use Loggable;
}

Common Pitfall: Overusing inheritance; prefer composition where appropriate.


6. Superglobals & Request Handling

6.1 Common Superglobals

  • $_GET: URL parameters
  • $_POST: Form data (POST requests)
  • $_SERVER: Server and execution environment info
  • $_SESSION: Session variables
  • $_COOKIE: HTTP cookies
  • $_FILES: Uploaded files
  • $_REQUEST: Combined GET, POST, and COOKIE data (avoid)

6.2 Form Handling Example

HTML Form (form.html):

<form action="process.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<button type="submit">Login</button>
</form>

PHP Processor (process.php):

<?php
// Always validate and sanitize!
$username = htmlspecialchars($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

// Validation
if (empty($username)) {
die("Username is required");
}

// Process login (example only - use password_hash() in production)
if ($username === "admin" && $password === "secret") {
session_start();
$_SESSION['user'] = $username;
echo "Welcome, $username!";
} else {
http_response_code(401);
echo "Invalid credentials";
}
?>

Security Best Practices:

  • Always validate input on the server side.
  • Sanitize output with htmlspecialchars() for HTML context.
  • Use filter_var() for validation/filtering.
  • Never trust user input!

7. Error Handling & Exceptions

7.1 Basic Error Handling

  • Errors: Traditional PHP errors (warnings, notices, fatals).
  • Exceptions: Object-oriented error handling (try/catch).

Code Snippet:

// Error reporting (development only!)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Exceptions
try {
$file = fopen("nonexistent.txt", "r");
if (!$file) {
throw new Exception("File not found");
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
// Log error
error_log($e->getMessage());
} finally {
echo "Always executes";
}

7.2 Custom Exceptions

Code Snippet:

class ValidationException extends Exception {
public function __construct($message, $code = 0) {
parent::__construct($message, $code);
}
}

function validateEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new ValidationException("Invalid email");
}
}

try {
validateEmail("bad-email");
} catch (ValidationException $e) {
echo "Validation failed: " . $e->getMessage();
}

7.3 Basic Logging

Code Snippet:

// PHP error log
error_log("User login failed", 3, "/var/log/myapp.log");

// Simple file logging
$logMessage = date('Y-m-d H:i:s') . " - User logged in\n";
file_put_contents('app.log', $logMessage, FILE_APPEND);

Best Practice: In production, log errors but don't display them to users.


8. Modern PHP Features (7.x – 8.x)

8.1 PHP 7.x Features

Type Declarations & Return Types:

function sum(float ...$numbers): float {
return array_sum($numbers);
}
echo sum(1, 2.5, 3); // 6.5

Nullable Types:

function findUser(?int $id): ?string {
return $id ? "User $id" : null;
}

Spaceship Operator:

echo 1 <=> 1; // 0 (equal)
echo 1 <=> 2; // -1 (less than)
echo 2 <=> 1; // 1 (greater than)

8.2 PHP 8.x Features

Union Types:

function display(int|string $value): void {
echo $value;
}
display(42); // OK
display("text"); // OK

Named Arguments:

function createUser($name, $age = 30, $country = "US") {
return "$name from $country, age $age";
}
// Skip optional parameters
echo createUser(name: "Alice", country: "UK");

Match Expression:

$status = 200;
$message = match($status) {
200, 201 => 'Success',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown',
};

Attributes (Annotations):

#[Route('/api/users', methods: ['GET'])]
class UserController {
#[Authorized(roles: ['admin'])]
public function listUsers() { /* ... */ }
}

Constructor Property Promotion:

class User {
public function __construct(
public string $name,
private int $age = 0
) {}
}
// Equivalent to manually declaring properties and assigning in constructor

Nullsafe Operator:

$country = $user?->getAddress()?->getCountry() ?? 'Unknown';
// Instead of: $country = $user && $user->getAddress() ? $user->getAddress()->getCountry() : 'Unknown';

Conclusion & Best Practices Summary

  1. Always sanitize user input and escape output.
  2. Use prepared statements for database queries (PDO/MySQLi).
  3. Follow PSR standards for coding style and autoloading.
  4. Use Composer for dependency management.
  5. Implement proper error handling (exceptions for application errors).
  6. Keep PHP updated for security and performance.
  7. Use modern PHP features (type hints, OOP) for maintainable code.
  8. Profile and optimize bottlenecks; use opcode caching (OPcache).

Additional Resources

Document Version: 1.0 • PHP 8.2+