Learn PHP Programming

Master PHP programming from basics to advanced concepts with our comprehensive tutorial series. Perfect for beginners and web developers.

PHP OOP Basics

Object-Oriented Programming organizes code into classes (blueprints) and objects (instances). OOP promotes code reuse, encapsulation, and maintainability — essential for building scalable applications.

Class with Properties, Constructor, and Methods

oop_basics.php
<?php
class Product {
    private string $name;
    private float $price;
    private int $stock;

    public function __construct(string $name, float $price, int $stock = 0) {
        $this->name  = $name;
        $this->price = $price;
        $this->stock = $stock;
    }

    public function getName(): string {
        return $this->name;
    }

    public function getPrice(): float {
        return $this->price;
    }

    public function isInStock(): bool {
        return $this->stock > 0;
    }

    public function purchase(int $quantity = 1): bool {
        if ($quantity > $this->stock) {
            return false;
        }
        $this->stock -= $quantity;
        return true;
    }

    public function getFormattedPrice(): string {
        return '$' . number_format($this->price, 2);
    }
}

// Creating and using objects
$laptop = new Product('Laptop Pro', 999.99, 15);
echo $laptop->getName();           // Laptop Pro
echo $laptop->getFormattedPrice(); // $999.99
echo $laptop->isInStock();         // true

$laptop->purchase(2);  // Buy 2 units
?>

A class bundles related data (properties) and behavior (methods) together. The constructor (__construct) initializes object state. Methods provide controlled access to internal data, keeping your object's invariants safe.

Access Modifiers: Public, Private, Protected

access_modifiers.php
<?php
class BankAccount {
    private string $owner;        // Only this class can access
    private float $balance = 0;   // Hidden from outside
    protected string $currency;   // This class + child classes

    public function __construct(string $owner, string $currency = 'USD') {
        $this->owner = $owner;
        $this->currency = $currency;
    }

    // Public: anyone can call
    public function deposit(float $amount): void {
        if ($amount <= 0) {
            throw new \InvalidArgumentException('Amount must be positive');
        }
        $this->balance += $amount;
        $this->logTransaction('deposit', $amount);
    }

    public function getBalance(): float {
        return $this->balance;
    }

    // Private: only this class can call
    private function logTransaction(string $type, float $amount): void {
        // Internal logging - not accessible from outside
        error_log("{$this->owner}: $type of $amount {$this->currency}");
    }
}

$account = new BankAccount('Alice');
$account->deposit(500.00);
echo $account->getBalance(); // 500.00

// $account->balance;         // ERROR: Cannot access private property
// $account->logTransaction(); // ERROR: Cannot access private method
?>

Public: accessible from anywhere. Private: only within the class itself. Protected: within the class and its subclasses. Start with private and only widen access when needed — this is the principle of least privilege.

Static Methods and Properties

static_members.php
<?php
class Database {
    private static ?Database $instance = null;
    private \PDO $connection;

    private function __construct(string $dsn) {
        $this->connection = new \PDO($dsn);
    }

    // Static method - called on the class, not an instance
    public static function getInstance(string $dsn = 'sqlite::memory:'): self {
        if (self::$instance === null) {
            self::$instance = new self($dsn);
        }
        return self::$instance;
    }

    public function query(string $sql): array {
        return $this->connection->query($sql)->fetchAll();
    }
}

// Usage - no "new" keyword needed
$db = Database::getInstance('sqlite:app.db');
$results = $db->query('SELECT * FROM users');

// Another example: utility class with static helpers
class StringHelper {
    public static function slugify(string $text): string {
        $text = strtolower(trim($text));
        $text = preg_replace('/[^a-z0-9-]/', '-', $text);
        return preg_replace('/-+/', '-', $text);
    }

    public static function truncate(string $text, int $length = 100): string {
        if (strlen($text) <= $length) return $text;
        return substr($text, 0, $length) . '...';
    }
}

echo StringHelper::slugify('Hello World!'); // hello-world-
?>

Static members belong to the class itself, not instances. Use self:: to reference them within the class. Static methods are good for utility functions and factory patterns. Avoid overusing them — they make testing harder because you can't easily mock them.

Constructor Promotion (PHP 8+)

constructor_promotion.php
<?php
// Traditional way (verbose)
class UserOld {
    private string $name;
    private string $email;
    private string $role;

    public function __construct(string $name, string $email, string $role = 'user') {
        $this->name = $name;
        $this->email = $email;
        $this->role = $role;
    }
}

// PHP 8+ Constructor Promotion (concise)
class User {
    public function __construct(
        private string $name,
        private string $email,
        private string $role = 'user',
        private readonly \DateTimeImmutable $createdAt = new \DateTimeImmutable()
    ) {}

    public function getName(): string { return $this->name; }
    public function getEmail(): string { return $this->email; }
    public function getRole(): string { return $this->role; }
}

// Readonly classes (PHP 8.2+) - all properties are implicitly readonly
readonly class Point {
    public function __construct(
        public float $x,
        public float $y
    ) {}

    public function distanceTo(Point $other): float {
        return sqrt(($this->x - $other->x) ** 2 + ($this->y - $other->y) ** 2);
    }
}

$p1 = new Point(0, 0);
$p2 = new Point(3, 4);
echo $p1->distanceTo($p2); // 5.0
// $p1->x = 10; // ERROR: Cannot modify readonly property
?>

Constructor promotion eliminates boilerplate by declaring and assigning properties directly in the constructor signature. Combined with readonly (PHP 8.1+) and readonly classes (PHP 8.2+), you get immutable value objects with minimal code.

Key Takeaways

  • Encapsulate data — make properties private and expose them through methods that enforce business rules.
  • Follow the Single Responsibility Principle — each class should have one reason to change.
  • Use type declarations everywhere — property types, parameter types, and return types make code self-documenting.
  • Prefer composition over inheritance — inject dependencies rather than extending base classes for code reuse.
  • Use constructor promotion (PHP 8+) and readonly properties to reduce boilerplate and enforce immutability.
Best Practice

Design your classes to be immutable where possible — use readonly properties and return new instances instead of modifying state. Immutable objects are easier to reason about, thread-safe, and eliminate entire categories of bugs related to unexpected state changes.

Frequently Asked Questions

PHP is a server-side scripting language designed for web development. It powers over 75% of websites on the internet, including Facebook, Wikipedia, and WordPress. Learning PHP opens doors to web development careers and freelance opportunities.

No, PHP is beginner-friendly with simple syntax. However, basic understanding of HTML and CSS will be helpful since PHP is often used to create dynamic web pages.

With PHP, you can build dynamic websites, web applications, content management systems, e-commerce platforms, APIs, and much more. Popular platforms like WordPress, Drupal, and Magento are built with PHP.

Basic PHP can be learned in 2-4 weeks with consistent practice. To become proficient and learn advanced concepts like frameworks and best practices, it typically takes 3-6 months of regular learning and practice.

You need a web server (Apache/Nginx), PHP interpreter, and a database (MySQL). The easiest way is to install XAMPP, WAMP, or MAMP which includes all these tools. You'll also need a text editor like VS Code or PhpStorm.

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)

VersionYearKey Features
PHP 5.02004Full OOP support, PDO, improved XML
PHP 7.020152x speed improvement, scalar type declarations, null coalesce operator
PHP 7.42019Arrow functions, typed properties, preloading
PHP 8.02020JIT compiler, named arguments, match expression, union types, attributes
PHP 8.12021Enums, fibers, readonly properties, intersection types
PHP 8.22022Readonly classes, DNF types, deprecate dynamic properties
PHP 8.32023Typed class constants, json_validate(), #[Override] attribute

How to Get Started with PHP

  1. Install a local environment — download XAMPP (Windows/Mac/Linux) or Laravel Valet (Mac). This gives you Apache, PHP, and MySQL in one package.
  2. Create your first file — make a file called index.php in your web root and add: <?php echo "Hello, World!"; ?>
  3. Run it in browser — start Apache and visit http://localhost/index.php to see output.
  4. Follow this tutorial series — work through each topic in order, running every example on your local setup.
  5. 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

Do I need to know HTML before learning PHP?

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.

Is PHP still relevant with frameworks like React/Next.js?

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.

Which PHP framework should I learn first?

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).

Can I run PHP code online without installing anything?

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.