PHP Classes/Objects

This tutorial helps you learn about PHP objects and how to define a class. Let's begin with what class and object are in general.

Object is an instance of a class. A class is a template for objects.

 

What is an OOP Case?

Take an assumption that you have a class named Fruit. The various properties a Fruit can have are name, weight, color, etc. So, you can define variables like $name, $weight, and $color to hold the values of these properties.

When you create individual objects (apple, banana, etc.), all the properties and behaviors will be inherited by them from the class. Still, each object will have different values for the properties.


Define a Class

You can define a class by using the class keyword, followed by the class name and curly braces pair ({}). All properties and methods of a class go inside the braces:

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

 

In the example below, a class named Fruit has been declared. It consists of two properties ($name and $color) and two methods set_name() and get_name() to set and get the $name property:

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

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

 

How To Define Objects?

Classes are nothing without objects! It is possible to create multiple objects from a class. Every object has all the properties and methods defined in the class, but the objects will have different property values.

You can create the objects of a class by using the new keyword.

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

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

  // 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();
?>

 

PHP - The $this Keyword

It refers to the current object and is only available inside methods.

Consider the following example:

<?php
class Fruit {
  public $name;
}
$apple = new Fruit();
?>

So, how can we change the value of the $name property? There are two ways to do this:

1. Inside the class (you can add a set_name() method and use $this):

<?php
class Fruit {
  public $name;
  function set_name($name) {
    $this->name = $name;
  }
}
$apple = new Fruit();
$apple->set_name("Apple");

echo $apple->name;
?>

 

2. Outside the class (by directly changing the property value):

<?php
class Fruit {
  public $name;
}
$apple = new Fruit();
$apple->name = "Apple";

echo $apple->name;
?>

 

PHP - instanceof

For checking if an object belongs to a specific class, you can use the instanceof keyword:

<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>