HOME HTML EDITOR C JAVA PHP

PHP What is OOP?

OOP stands for Object-Oriented Programming. Procedural programming is about writing procedures or functions that perform operations on data, while object-oriented programming is about creating objects that contain both data and functions.

1. The Concept of Classes and Objects

Think of a Class as a blueprint (like a drawing of a car) and an Object as the actual thing built from that blueprint (like a specific Toyota or Ford car).

2. Why Use OOP?

OOP is faster and easier to execute. It provides a clear structure for programs and helps to keep the PHP code DRY ("Don't Repeat Yourself").

3. A Simple Class Example

To define a class, use the class keyword followed by the name of the class.

<?php
class Fruit {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}

// Create an Object
$apple = new Fruit();
$apple->set_name('Apple');
echo $apple->get_name();
?>

4. The $this Keyword

The $this keyword refers to the current object. It is only available inside methods and is used to access the properties or methods of the class from within.

5. The Four Pillars of OOP

To master PHP OOP, you will eventually learn these four main concepts:

  1. Inheritance: A class can derive properties and methods from another class.
  2. Encapsulation: Wrapping data and code into a single unit and restricting access.
  3. Abstraction: Hiding complex implementation details and showing only the necessary features.
  4. Polymorphism: Allowing different classes to be treated as instances of the same parent class through the same interface.
Tip: In a large project, OOP makes your code much more organized. Instead of having one giant file with hundreds of functions, you have many small, manageable classes.