Learn PHP Programming
Master PHP programming from basics to advanced concepts with our comprehensive tutorial series. Perfect for beginners and web developers.
PHP Classes & Objects
Classes are blueprints for creating objects. They encapsulate data (properties) and behavior (methods) into reusable units. PHP supports typed properties, constructors with promotion, visibility modifiers, magic methods, and named arguments (PHP 8+).
1. Full Class with Typed Properties, Constructor & Business Method
<?php
declare(strict_types=1);
class Product {
// Typed properties (PHP 7.4+)
private string $name;
private float $price;
private int $quantity;
private string $sku;
public function __construct(
string $name,
float $price,
int $quantity = 0,
string $sku = ''
) {
if ($price < 0) {
throw new \InvalidArgumentException('Price cannot be negative');
}
$this->name = $name;
$this->price = $price;
$this->quantity = $quantity;
$this->sku = $sku;
}
// Getter methods
public function getName(): string { return $this->name; }
public function getPrice(): float { return $this->price; }
public function getQuantity(): int { return $this->quantity; }
// Setter with validation
public function setQuantity(int $qty): void {
if ($qty < 0) {
throw new \InvalidArgumentException('Quantity cannot be negative');
}
$this->quantity = $qty;
}
// Business logic method
public function getTotalValue(): float {
return $this->price * $this->quantity;
}
public function applyDiscount(float $percent): void {
$this->price -= $this->price * ($percent / 100);
}
}
// Usage
$product = new Product('Laptop', 999.99, 5, 'LAP-001');
echo $product->getName(); // Laptop
echo $product->getTotalValue(); // 4999.95
$product->applyDiscount(10);
echo $product->getTotalValue(); // 4499.96
?>
2. Magic Methods (__toString, __get, __set)
<?php
class DynamicEntity {
private array $data = [];
public function __construct(private string $type) {}
// Called when accessing inaccessible properties
public function __get(string $name): mixed {
return $this->data[$name] ?? throw new \RuntimeException("No property: {$name}");
}
// Called when setting inaccessible properties
public function __set(string $name, mixed $value): void {
$this->data[$name] = $value;
}
// Called when using isset() on inaccessible properties
public function __isset(string $name): bool {
return isset($this->data[$name]);
}
// Called when object is cast to string
public function __toString(): string {
return "{$this->type}: " . json_encode($this->data);
}
}
$user = new DynamicEntity('User');
$user->name = 'Alice'; // __set
$user->email = 'a@test.com'; // __set
echo $user->name; // __get → Alice
echo $user; // __toString → User: {"name":"Alice","email":"a@test.com"}
?>
3. Object Cloning & Comparison (clone, == vs ===)
<?php
class Address {
public function __construct(public string $street, public string $city) {}
}
class Customer {
public function __construct(
public string $name,
public Address $address
) {}
// Deep clone nested objects to avoid shared references
public function __clone(): void {
$this->address = clone $this->address;
}
}
$original = new Customer('Alice', new Address('123 Main', 'NYC'));
$copy = clone $original; // Triggers __clone
$copy->name = 'Bob';
$copy->address->city = 'LA';
echo $original->address->city; // NYC (deep clone preserved original)
echo $copy->address->city; // LA
// Comparison operators
$a = new Customer('Alice', new Address('1 St', 'NYC'));
$b = new Customer('Alice', new Address('1 St', 'NYC'));
$c = $a;
var_dump($a == $b); // true — same property values
var_dump($a === $b); // false — different instances
var_dump($a === $c); // true — same instance reference
?>
4. Named Arguments in Constructors (PHP 8+)
<?php
class DatabaseConfig {
public function __construct(
private string $host = 'localhost',
private int $port = 3306,
private string $database = 'app',
private string $charset = 'utf8mb4',
private bool $persistent = false
) {}
public function getDsn(): string {
return "mysql:host={$this->host};port={$this->port};" .
"dbname={$this->database};charset={$this->charset}";
}
}
// Named arguments: skip defaults, pass in any order
$config = new DatabaseConfig(
database: 'shop_db',
persistent: true,
port: 5432
);
echo $config->getDsn();
// mysql:host=localhost;port=5432;dbname=shop_db;charset=utf8mb4
// Constructor promotion + named args = concise object creation
class Point {
public function __construct(
public readonly float $x,
public readonly float $y,
public readonly float $z = 0.0
) {}
}
$p = new Point(y: 10.5, x: 3.2);
echo "{$p->x}, {$p->y}, {$p->z}"; // 3.2, 10.5, 0.0
?>
Key Takeaways
- Typed properties (PHP 7.4+) enforce data types at compile time, catching bugs before runtime.
- Magic methods (__get, __set, __toString, __clone) customize how objects behave for property access, string conversion, and copying.
- Object cloning with __clone ensures deep copies of nested objects, preventing unintended shared references.
- Comparison:
==compares property values;===checks if two variables point to the exact same instance. - Named arguments (PHP 8+) make constructors with many parameters readable — skip defaults and pass in any order.
readonly properties when state should not change after construction.
Frequently Asked Questions
PHP Programming Tutorial — Learn PHP from Scratch
PHP (PHP: Hypertext Preprocessor) is the most widely-used server-side scripting language for web development. It powers over 77% of all websites with known server-side languages, including WordPress, Facebook, Wikipedia, and Slack. This comprehensive tutorial series takes you from complete beginner to confident PHP developer with hands-on examples you can run and modify.
Each topic in this tutorial includes multiple runnable code examples with line-by-line explanations, best practice tips, and navigation to the next logical concept. Whether you are learning PHP for the first time or refreshing your knowledge of a specific feature, every page is designed to give you practical, immediately-usable code.
What You Will Learn in This PHP Tutorial
- Basics: Syntax, variables, constants, data types, operators
- Strings & Arrays: Manipulation, searching, sorting, multidimensional arrays
- Control Flow: if/else, switch, for, while, foreach loops
- Functions: Parameters, return values, scope, anonymous functions
- Superglobals: $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER
- Forms: Handling user input, validation, file uploads
- File Handling: Reading, writing, and manipulating files
- Sessions & Cookies: User state management across requests
- OOP: Classes, objects, inheritance, interfaces, traits
- Error Handling: try/catch, custom exceptions, error reporting
- Database: MySQL connection, CRUD operations, prepared statements
- Security: SQL injection prevention, XSS, CSRF, password hashing
Why Learn PHP in 2026?
Despite the rise of Node.js and Python, PHP remains the backbone of web development for compelling reasons:
- Job market demand: Thousands of PHP developer positions available globally. WordPress alone powers 43% of all websites and requires PHP.
- Framework ecosystem: Laravel (the most popular web framework), Symfony, CodeIgniter, and Slim provide professional-grade tooling.
- Low barrier to entry: Shared hosting supports PHP out of the box. No complex server configuration needed to get started.
- PHP 8.x improvements: JIT compiler, named arguments, match expressions, union types, fibers — modern PHP is fast and expressive.
- CMS dominance: WordPress, Drupal, Joomla, Magento, WooCommerce all run on PHP. Knowing PHP gives you access to this entire ecosystem.
- Freelancing opportunities: PHP projects dominate freelance platforms. Many small businesses need WordPress customisation and PHP-based solutions.
PHP Version History (Key Milestones)
| Version | Year | Key Features |
|---|---|---|
| PHP 5.0 | 2004 | Full OOP support, PDO, improved XML |
| PHP 7.0 | 2015 | 2x speed improvement, scalar type declarations, null coalesce operator |
| PHP 7.4 | 2019 | Arrow functions, typed properties, preloading |
| PHP 8.0 | 2020 | JIT compiler, named arguments, match expression, union types, attributes |
| PHP 8.1 | 2021 | Enums, fibers, readonly properties, intersection types |
| PHP 8.2 | 2022 | Readonly classes, DNF types, deprecate dynamic properties |
| PHP 8.3 | 2023 | Typed class constants, json_validate(), #[Override] attribute |
How to Get Started with PHP
- Install a local environment — download XAMPP (Windows/Mac/Linux) or Laravel Valet (Mac). This gives you Apache, PHP, and MySQL in one package.
- Create your first file — make a file called
index.phpin your web root and add:<?php echo "Hello, World!"; ?> - Run it in browser — start Apache and visit
http://localhost/index.phpto see output. - Follow this tutorial series — work through each topic in order, running every example on your local setup.
- Build a project — after completing basics through OOP, build a simple CRUD app (todo list, blog, or contact form) to solidify your knowledge.
Frequently Asked Questions
Basic HTML knowledge is helpful since PHP is often embedded in HTML pages. You do not need to be an HTML expert — understanding tags, forms, and page structure is enough to start.
Yes. PHP and React serve different roles. React is frontend; PHP is backend. Laravel (PHP) is often used as the API backend for React frontends. WordPress (PHP) powers 43% of the web. The job market for PHP developers remains strong.
Laravel is the most popular and has the best documentation, ecosystem, and community. Learn core PHP first (this tutorial), then move to Laravel. Other options: Symfony (enterprise), CodeIgniter (lightweight), Slim (microframework for APIs).
Yes. Use our free online code editors to write and execute PHP code directly in your browser. This is perfect for learning and testing snippets without local setup.
Who Is This Tutorial For?
Complete beginners who want to learn their first programming language for web development. Self-taught developers filling gaps in their PHP knowledge. Students preparing for web development courses or exams. WordPress developers who want to understand the PHP underneath themes and plugins. Backend developers from other languages (Python, Node.js) learning PHP for a new project. Anyone preparing for PHP developer job interviews.
Master PHP Programming with Our Comprehensive Tutorial
Our PHP programming tutorial is designed to take you from a complete beginner to an advanced PHP developer. Whether you're looking to build dynamic websites, create web applications, or start a career in web development, this tutorial series provides everything you need to succeed.
What You'll Learn
- PHP fundamentals and syntax
- Variables, data types, and operators
- Control structures and loops
- Functions and arrays
- Object-oriented programming
- Database integration with MySQL
- Web forms and user input handling
- Security best practices
PHP remains one of the most popular programming languages for web development, powering millions of websites worldwide. Our tutorial includes practical examples, real-world projects, and best practices to ensure you learn not just the syntax, but how to write clean, efficient, and secure PHP code.