PHP Objects.


Definition and Usage

In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.

Primary (scalar) variables, arrays and other objects can be cast to object data type using casting operator. PHP provides stdClass as a generic empty class which is useful for adding properties dynamically and casting.

Syntax

To declare an object of a class we need to use new statement

class myclass
{
   ..
   ..
}
$obj=new myclass;

Example

 Live Demo

<?php
class SayHello{
   function hello(){
      echo "Hello World";
   }
}
$obj=new SayHello;
$obj->hello();
?>

Output

This will produce following result −

Hello World

Object of stdClass is null to begin with. We can add properties dynamically

Example

 Live Demo

<?php
$obj=new stdClass;
$obj->name="Deepak";
$obj->age=21;
$obj->marks=75;
print_r($obj);
?>

Output

This will produce following result −

stdClass Object(
   [name] => Deepak
   [age] => 21
   [marks] => 75
)

Array can be typecast to object as follows

Example

 Live Demo

<?php
$arr=array("name"=>"Deepak", "age"=>21, "marks"=>75);
$obj=(object)$arr;
print_r($obj);
?>

Output

This will produce following result −

stdClass Object(
   [name] => Deepak
   [age] => 21
   [marks] => 75
)

Conversely, an object can be cast to array

Example

 Live Demo

<?php
$obj=new stdClass;
$obj->name="Deepak";
$obj->age=21;
$obj->marks=75;
$arr=(array)$obj;
print_r($arr);
?>

Output

This will produce following result −

Array(
   [name] => Deepak
   [age] => 21
   [marks] => 75
)

Variable of any scalar type can also be converted to an object by type casting. Value of scalar variable becomes value of object's scalar property.

Example

 Live Demo

<?php
$name="Deepak";
$age=21;
$percent=75.50;
$obj1=(object)$name;
print_r($obj1);
$obj2=(object)$age;
print_r($obj2);
$obj3=(object)$percent;
print_r($obj3);
?>

Output

This will produce following result −

stdClass Object(
   [scalar] => Deepak
)
stdClass Object(
   [scalar] => 21
)
stdClass Object(
   [scalar] => 75.5
)

Updated on: 04-Oct-2023

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements