Objects in PHP

In PHP, everything in object-oriented programming (OOP) revolves around the creation of classes and objects. An object in programming is a specific instance of a class. Each instance of an object holds its own relevant data or value.

An entity that has state and behavior is called an object in PHP. Here, the state represents the properties or attributes, and the behavior represents the methods or functions. Hence, objects in PHP consist of properties (data members) and behaviors (member functions or methods).

Characteristics of Objects in PHP


There are three main characteristics of objects in PHP:

1. State

  • The state of an object represents the specific data or values stored in its member variables.
  • It is also known as the properties, attributes, or data members of the object.
  • The state of an object is represented by variables.
  • During the execution of a program, the state of an object can change when its properties are modified.

Example:

$car->color = "Red"; // state = Red
$car->color = "Blue"; // state changed to Blue

2. Behavior

  • The behavior of an object defines what the object can do or what actions it can perform.
  • It is represented by methods (functions) inside the class.
  • Methods are used to modify the state of the object or perform operations using its data.

Example:

$car->startEngine(); // behavior (method)

Here, startEngine() is a method that defines a behavior or action of the Car object.

3. Identity

  • The identity represents the unique name of an object.
  • It differentiates one object from the other even if they have the same state and behavior.
  • The unique name of an object is used to identify the object.

Let’s understand these key characteristics of an object with the help of real-world examples.

Real-Time Example of Objects in PHP


An object can represent anything in the real world that has properties (state) and behaviors (actions). For example: a Person, Book, Pen, Car, Mobile Phone, or TV — all can be represented as objects in PHP.

Real-Time Example 1: Person Object

Let’s take a real-world example of a Person as an object.

An object “Person” has three main characteristics:

  • Identity – Represents the name of person.
  • State – Represents properties or attributes of a person, such as hair color, eye color, height, etc. These are represented by variables such as
$name = "John";
$hairColor = "black";
$eyeColor = "brown";
$height = "5.9ft";
$weight = "70kg";
  • Behavior – Represents actions such as eat, sleep, walk, and study. These are represented by methods, such as eat(), sleep(), walk(), and study().

Thus, when properties and behaviors are combined together of any real-world object, make an object in PHP.

Real-Time Example 2: Pencil Object

Let’s take another simple example — a Pencil. A pencil is an object. Its name is Natraj.

  • State: color is black.
  • Behavior: It is used to write. So, writing is behavior.

Thus, you can take any object around you and think about what property it has? And what action it does?

Note:
  • Nouns in English represent properties or states of an object. We can represent it with the help of variables.
  • Verbs represent actions/behaviors, which we can represent with the help of methods or functions.

Syntax to Create an Object of a Class in PHP


You can create an object or instance of class using the new keyword followed by the class name. The general syntax to create an object of the class in PHP is:

$object_name = new ClassName();

In the above syntax,

  • ClassName is the name of a class.
  • $student is the object reference variable.
  • new is a keyword which creates an instance of the class in memory.

Example:

$student = new Student();

This line of code creates a new Student object and assigns it to the variable $student. Here,

  • Student is the class name.
  • $student is the object.
  • The new keyword tells PHP to create a new instance of the Student class in the memory.

Creation of Multiple Objects in PHP

You can create multiple objects of the same class like this:

// Creating of multiple objects.
$student1 = new Student("Deepak", 21, "B.Tech");
$student2 = new Student("Priya", 22, "MBA");

Object Memory Representation


When you create an object of the class in PHP:

  • PHP allocates a unique memory address for that object.
  • The object reference variable (such as $student1) holds the reference (or address) to that memory location, not the object itself.
  • Even if you create two objects of the same class, they are stored in different memory locations. Each location has its own unique identity.

Example:

<?php
class Student {
public $name;
}

$student1 = new Student();
$student2 = new Student();

echo "ID of student1: " . spl_object_id($student1) . "\n";
echo "ID of student2: " . spl_object_id($student2) . "\n";

// Comparing objects.
var_dump($student1 === $student2);
?>

Output:

ID of student1: 1
ID of student2: 2
bool(false)

Although both $student1 and $student2 are instances of the same class Student. Each object ($student1 and $student2) has a different internal ID, which shows they are stored at different memory locations. Hence, they are not identical objects. The comparison $student1 === $student2 returns false because even though both are instances of the same class, they are different objects.

In PHP, you cannot directly get or view the memory address of an object. PHP intentionally hides low-level memory details because it is a high-level, managed scripting language (unlike C++).

However, each object in PHP has a unique identification number that behaves like a memory address. You can get this unique ID using the spl_object_id() function, which returns a unique integer ID for each object during the script execution.

Accessing Object Members of a Class


Once you have created an object, you can access its properties and methods using the object reference variable along with the arrow operator (->).

Syntax for Accessing Properties:

$object->propertyName;

Syntax for Accessing Methods:

$object->methodName();

In the above syntax, the -> is an arrow operator, which is used to access class members (properties and methods) of an object. It is also called object operator. This operator connects an object variable with its property or method.

Example:

<?php
class Car {
    public $brand = "Toyota";

    public function startEngine() {
       echo "The engine has started!";
   }
}
// Creating an object of Car class.
$myCar = new Car();

// Accessing property.
echo $myCar->brand; 

// Accessing method.
$myCar->startEngine();
?>

Output:

Toyota
The engine has started!

In this example,

  • $myCar → An object of class Car.
  • $myCar->brand → Accessing the property brand of the object.
  • $myCar->startEngine() → Calling the method startEngine() of the object.

How Properties and Methods Are Stored in PHP Objects?


When you create an object, PHP allocates separate memory for its properties (variables). Therefore, each object holds its own copy of data.

However, methods belong to the class definition itself, so they are shared among all objects of the class. PHP does not duplicate them in memory for each object.

Real-world Examples of Objects in PHP


Let’s take some real-word examples based on the objects in PHP.

Example 1:

<?php
class Student {
// Declaration of properties.
   public $name;
   public $age;
   public $course;

// Declaration of constructor.
   public function __construct($name, $age, $course) {
      $this->name = $name;
      $this->age = $age;
      $this->course = $course;
   }

// Declaration of method.
   public function showDetails() {
       echo "Name: {$this->name}, Age: {$this->age}, Course: {$this->course} \n";
   }
}

// Creating objects of class Student.
$student1 = new Student("Deepak", 21, "B.Tech");
$student2 = new Student("Priya", 22, "MBA");

// Accessing methods of the object.
$student1->showDetails();
$student2->showDetails();
?>

Output:

Name: Deepak, Age: 21, Course: B.Tech
Name: Priya, Age: 22, Course: MBA

In this example, we have created a class named Student that defines three properties. Then, we have declared a constructor to initialize them. After that, we have created a method named showDetails() which displays the object data.

We have created two different objects ($student1 and $student2) with different property values. Each object represents a unique real-world entity with its own state and behavior.

Example 2:

<?php
class Person {
// State (Properties).
   public $name;
   public $hairColor;
   public $eyeColor;

// Declare a constructor to initialize object.
   public function __construct($name, $hairColor, $eyeColor) {
      $this->name = $name;
      $this->hairColor = $hairColor;
      $this->eyeColor = $eyeColor;
   }

// Behavior (Methods)
   public function eat() {
      echo "{$this->name} is eating.<br>";
   }
   public function sleep() {
      echo "{$this->name} is sleeping.<br>";
   } 
   public function walk() {
      echo "{$this->name} is walking.<br>";
   }
   public function study() {
      echo "{$this->name} is studying.<br>";
   }
}

// Creating an object of class Person.
$person1 = new Person("John", "Black", "Brown");

// Accessing state (properties).
echo "Name: {$person1->name}<br>";
echo "Hair Color: {$person1->hairColor}<br>";
echo "Eye Color: {$person1->eyeColor}<br>";

// Calling behavior (methods).
$person1->eat();
$person1->sleep();
$person1->walk();
$person1->study();
?>

Output:

Name: John
Hair Color: Black
Eye Color: Brown
John is eating.
John is sleeping.
John is walking.
John is studying.

Example 3:

<?php
class Pencil {
   public $brand;
   public $color;

   public function __construct($brand, $color) {
     $this->brand = $brand;
     $this->color = $color;
   }

   public function write() {
      echo "The {$this->brand} pencil is writing.<br>";
   }

   public function draw() {
      echo "The {$this->brand} pencil is drawing.<br>";
   }
}

// Creating an object of class Pencil.
$pencil1 = new Pencil("Natraj", "Black");

// Accessing state and behavior.
echo "Pencil Brand: {$pencil1->brand}<br>";
echo "Pencil Color: {$pencil1->color}<br>";
$pencil1->write();
$pencil1->draw();
?>

Output:

Pencil Brand: Natraj
Pencil Color: Black
The Natraj pencil is writing.
The Natraj pencil is drawing.

Conclusion

Objects are the fundamental building blocks of Object-Oriented Programming in PHP. Understanding the concept of objects is essential for beginners to learn OOP in PHP because they allow you to write cleaner, scalable, and reusable code. We hope these examples have helped you grasp how to create and use objects effectively in PHP.