PHP Objects (original) (raw)

Last Updated : 17 Apr, 2025

An object in PHP is an instance of a class. Objects are used to store data (properties) and define behaviors (methods) that can be used within an application. An object is created using the new keyword followed by the class name.

**Syntax:

$objectName = new ClassName();

**Now, let us understand with the help of the example:

PHP `

this−>brandthis->brand this>brandthis->model."; } } // Create an object (instance) of the Car class $myCar = new Car(); $myCar->brand = "Toyota"; // Set the brand property $myCar->model = "Corolla"; // Set the model property // Access the method of the object $myCar->drive(); ?>

`

Output

Driving the Toyota Corolla.

**In this example:

The $this Keyword

The $this keyword is used inside a class to refer to the current object. It allows you to access the object’s properties and methods from within the class.

**Now, let us understand with the help of the example:

PHP `

this−>brand=this->brand = this>brand=brand; // Using $this to refer to the current object's property } public function displayInfo() { echo "Car brand: this−>brand";//Usingthis->brand"; // Using this>brand";//Usingthis to access the brand property } } $myCar = new Car("Ford"); $myCar->displayInfo(); // Output: Car brand: Ford ?>

`

**In this example:

Using instanceof to Check Object Types

The instanceof operator checks whether an object is an instance of a specific class or implements a particular interface. It can be useful when you want to check the type of an object before performing certain actions.

**Now, let us understand with the help of the example:

PHP `

this−>name=this->name = this>name=name; } } class Dog extends Animal { public function speak() { echo "$this->name barks."; } } $dog = new Dog("Rex"); if ($dog instanceof Dog) { echo "$dog->name is a Dog!"; // Output: Rex is a Dog! } else { echo "$dog->name is not a Dog!"; } ?>

`

**In this example:

Best Practices for Using PHP objects

Conclusion

PHP objects are a core concept of Object-Oriented Programming (OOP), providing a way to structure and manage your code. By using classes and objects, you can easily create reusable components and maintainable code.