An Introduction to Classes and Objects in PHP 8+

What is OOP?

Object-oriented programming (OOP) is a computer programming model that organizes software design around objects rather than single functions. An object can be defined as a data field that has unique attributes and behavior.

A class is a container for objects to be manipulated using methods (internal functions).

OOP

Let’s assume we have a class named Fruit. A Fruit can have properties like name, colour, weight, etc. We can define variables like $name, $colour, and $weight to hold the values of these properties.

When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

Define a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({ }). All its properties and methods go inside the braces:

<?php
class Fruit {
  // code goes here...
}
?>

Below we declare a class named Fruit consisting of two properties ($name and $colour) and two methods set_name() and get_name() for setting and getting the $name property:

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

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

Note: In a class, variables are called properties and functions are called methods!

Define Objects

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.

Objects of a class is created using the new keyword.

In the example below, $apple and $banana are instances of the class Fruit:

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

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

$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *