Mastering PHP: From Basics to Building Dynamic Web Applications

0 0 0 0 0

Chapter 8: OOP in PHP & Final Project

🔹 1. Introduction

Object-Oriented Programming (OOP) in PHP allows you to organize code logically, reuse components, and scale efficiently. In this chapter, you'll learn PHP's OOP features and apply them in a final project — a basic Content Management System (CMS).


🔹 2. What Is OOP?

OOP organizes code around objects, which are instances of classes. A class defines the properties (data) and methods (functions) of the object.

Key OOP Concepts:

Concept

Description

Class

A blueprint for objects

Object

An instance of a class

Property

A variable inside a class

Method

A function inside a class

Constructor

Method that runs when an object is created

Inheritance

Allows a class to inherit from another

Access Modifiers

Control visibility of class members (public, protected, private)


🔹 3. Declaring Classes and Objects

Basic Class:

class User {

  public $name = "Guest";

 

  public function sayHello() {

    return "Hello, " . $this->name;

  }

}

 

$user1 = new User();

$user1->name = "Alice";

echo $user1->sayHello(); // Hello, Alice


🔹 4. Constructors & __construct()

A constructor automatically runs when an object is created.

class Product {

  public $name;

  public $price;

 

  function __construct($name, $price) {

    $this->name = $name;

    $this->price = $price;

  }

 

  function display() {

    return "$this->name costs $this->price";

  }

}

 

$p = new Product("Laptop", 900);

echo $p->display();


🔹 5. Inheritance & Overriding

class Animal {

  public function makeSound() {

    echo "Some sound";

  }

}

 

class Dog extends Animal {

  public function makeSound() {

    echo "Bark!";

  }

}

 

$dog = new Dog();

$dog->makeSound(); // Bark!


🔹 6. Access Modifiers

Modifier

Visibility

public

Accessible from anywhere

protected

Accessible within class & subclasses

private

Accessible only within the class

class User {

  private $email;

 

  public function setEmail($email) {

    $this->email = $email;

  }

 

  public function getEmail() {

    return $this->email;

  }

}


🔹 7. Static Methods and Properties

Use static when a method or property doesn’t need a specific object.

class Math {

  public static function square($n) {

    return $n * $n;

  }

}

 

echo Math::square(5); // 25


🔹 8. Interfaces and Traits

Interface:

interface Logger {

  public function log($msg);

}

 

class FileLogger implements Logger {

  public function log($msg) {

    echo "Log: $msg";

  }

}

Trait:

trait Sharable {

  public function share() {

    echo "Shared!";

  }

}

 

class Post {

  use Sharable;

}


🔹 9. Final Project: Mini CMS (CRUD for Posts)

Structure:

/cms

  ── config.php

  ── Post.php

  ── index.php

  ── create.php

  ── update.php

  ── delete.php


config.php

<?php

$conn = new mysqli("localhost", "root", "", "cms");

if ($conn->connect_error) die("DB Error");

?>


Post.php (Model Class)

class Post {

  private $conn;

 

  public function __construct($db) {

    $this->conn = $db;

  }

 

  public function getAll() {

    return $this->conn->query("SELECT * FROM posts");

  }

 

  public function create($title, $body) {

    $stmt = $this->conn->prepare("INSERT INTO posts (title, body) VALUES (?, ?)");

    $stmt->bind_param("ss", $title, $body);

    return $stmt->execute();

  }

 

  public function get($id) {

    return $this->conn->query("SELECT * FROM posts WHERE id=$id")->fetch_assoc();

  }

 

  public function update($id, $title, $body) {

    $stmt = $this->conn->prepare("UPDATE posts SET title=?, body=? WHERE id=?");

    $stmt->bind_param("ssi", $title, $body, $id);

    return $stmt->execute();

  }

 

  public function delete($id) {

    return $this->conn->query("DELETE FROM posts WHERE id=$id");

  }

}


index.php (Read All)

require 'config.php';

require 'Post.php';

$post = new Post($conn);

$posts = $post->getAll();

 

while($row = $posts->fetch_assoc()) {

  echo "<h3>{$row['title']}</h3>";

  echo "<p>{$row['body']}</p><hr>";

}

You can add similar pages for:

  • create.php — form to add a post
  • update.php — edit existing post
  • delete.php — delete a post by ID

The project uses:

  • OOP for model structure
  • MySQL for storage
  • Forms and file separation for MVC-like structure

Summary Table: OOP & CMS Concepts

Concept

Usage

Class

Blueprint for objects

Object

$user = new User()

Method

$user->sayHello()

Constructor

__construct() to initialize

Inheritance

class Dog extends Animal

Static Method

Math::square(5)

Trait

use Sharable

Prepared SQL

bind_param("ssi", $a, $b, $c)



Back

FAQs


1. What is PHP used for?

PHP is primarily used for creating dynamic web pages and server-side applications such as login systems, e-commerce platforms, and CMSs.

2. Is PHP still relevant in 2025?

Absolutely. PHP continues to power most of the web and is essential in WordPress, Laravel, and web hosting environments.

3. Do I need to install anything to run PHP?

Yes — you can install XAMPP, MAMP, Laragon, or PHP CLI for local development.

4. What databases work with PHP?

MySQL is the most commonly used with PHP, but it also supports PostgreSQL, SQLite, and others.

5. What’s the difference between PHP and JavaScript?

PHP is a server-side scripting language, while JavaScript is primarily client-side, running in the browser.

6. Can I use PHP with HTML?

Yes PHP is often embedded inside HTML to create dynamic pages

7. What is a PHP file extension?

PHP files have the .php extension and are executed on the server.

8. How do I send data from a form to PHP?

Use method="POST" or method="GET" in your form and access data in PHP using $_POST or $_GET.

9. Is PHP good for building APIs?

Yes — PHP can be used to build RESTful APIs, especially with frameworks like Laravel or Slim.

10. What are some popular PHP frameworks?

Laravel, Symfony, CodeIgniter, Zend, and Slim are among the most used PHP frameworks.