What is an object in PHP?
In PHP, objects can be related to the entities in real life It considers everything that we can see around us, as an object that has some attributes. An object is an instance of a class. It's created from a class blueprint using the new keyword followed by the class name, optionally passing arguments to the constructor if it's defined. Objects have properties (attributes) and methods defined by their class.
Multiple objects can be created from the same class, each having its own set of property values. Objects allow you to work with specific instances of a class, allowing for data encapsulation and code reuse.
- An object is an instance of class.
- Objects have properties (attributes) and methods defined by their class.
- An object is something that is used to perform a set of related activities.
- We can define a class once and then create one or more objects that belong to it.
- Multiple objects can be created from the same class, each having its own set of property values.
- An Object is an individual instance of the data structure defined by a class.
- Class methods and properties can be accessed directly through object instances.
- We we use the connector (Dot operator->) symbol to connect objects to their properties or methods.
Example1:
<?php
class Office
{
// Class properties
// methods go here
}
$obj = new Office;
var_dump($obj);
?
Example 2
<?php
class Office{
public function Chair_name(){
echo "This is Desk Chair"."<br>";
}
public function price(){
echo "RS- 500";
}
}
$obj = new Office();
$obj->chair_name();
$obj->price();
?>
Output
This is Desk Chair
RS- 500
Example 3
<?php
class Room
{
private $name= "Kitchen Room";
public function display(){
echo $this->name;
}
}
$obj = new Room();
$obj->display();
? >
Output
Kitchen Room
Prev Next