Skip to main content

PHP OOP Classes and Objects

A class works like a template: it describes the structure (properties) and behavior (methods) that its objects will have. Each object is then one individual instance of that class.


Define a Class

To define a class, write the class keyword, then the class name, then a pair of curly braces ({}). Everything that belongs to the class, properties and methods alike, goes between those braces.

Imagine a class called Fruit. It could store a name and a color as properties, and offer two methods: one that sets those details and one that gets them.

Note: A property is simply a variable that lives inside a class, and a method is a function that lives inside a class.

Note: Inside a method, $this stands for the current object, giving you access to its own properties and methods.

Class Definition

The Fruit class, with its properties and methods:

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

  // Method to set the properties
  function set_details($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }

  // Method to display the properties
  function get_details() {
    echo "Name: " . $this->name . ". Color: " . $this->color .".<br>";
  }
}
?>

Define Objects

A class does nothing useful until you create objects from it. One class can produce as many objects (instances) as you need. All of them get the properties and methods the class defines, but each one stores its own property values.

You create an object with the new keyword.

Creating Objects

Here, the Fruit class produces two separate objects, $apple and $banana:

Prompt
Write a PHP script that defines a Fruit class with public properties $name and $color, methods set_details() and get_details(), then creates two objects ($apple and $banana) and displays their details.
Output: PHP script

PHP - instanceof

Need to find out whether an object belongs to a particular class? The instanceof keyword answers that question:

instanceof Example

Here, instanceof tests whether $apple belongs to the Fruit class, and var_dump() shows the answer:

Prompt
Write a PHP script that creates a Fruit object and uses var_dump() with instanceof to check if it belongs to the Fruit class.
Output: PHP script