PHP ยท Chapter 35 of 44

PHP OOP: Classes & Objects

Object-Oriented Programming (OOP) organizes code around classes, which act as blueprints for objects. A class defines properties (data) and methods (functions) that describe and control the behavior of its objects.

An object is a specific instance created from a class using the new keyword. Each object has its own copy of the class's properties, while sharing the same defined methods.

Syntax
class MyClass {
  public $property;
  function myMethod() { }
}
$obj = new MyClass();

Defining a class

A class is defined with the class keyword, followed by its name and a body containing properties and methods, such as class Car { public $color; }.

Creating objects

An object is created with new ClassName(). You access its properties and methods using the -> (arrow) operator, like $car->color or $car->drive().

Example 1 (php)
<?php
  class Car {
    public $color = "red";
    function describe() {
      return "This car is " . $this->color;
    }
  }
  $car = new Car();
  echo $car->describe();
?>
Output
This car is red

$this refers to the current object, letting the method access its own property.

Example 2 (php)
<?php
  class Counter {
    public $count = 0;
    function increment() {
      $this->count++;
    }
  }
  $c = new Counter();
  $c->increment();
  $c->increment();
  echo $c->count;
?>
Output
2

Each call to increment() updates the object's own count property using $this.

Key points

  • A class is a blueprint for creating objects.
  • An object is an instance of a class created with new.
  • $this refers to the current object inside a class method.
  • The -> operator accesses an object's properties and methods.
๐Ÿ’ก Note: Group related data and behavior together in a class to keep your code organized and reusable.

๐Ÿ“ Quick Quiz

1. What keyword creates a new object from a class?

2. What does $this refer to inside a class method?

3. Which operator accesses an object's property?