PHP Objects.

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;

Creating Objects from Custom Classes

Here's how to create an object from a user-defined class ?

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

Using stdClass for Dynamic Properties

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

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

Type Casting to Objects

Array to Object

Array can be typecast to object as follows ?

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

Object to Array

Conversely, an object can be cast to array ?

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

Scalar Values to Objects

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 ?

<?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);
?>
stdClass Object
(
    [scalar] => Deepak
)
stdClass Object
(
    [scalar] => 21
)
stdClass Object
(
    [scalar] => 75.5
)

Conclusion

PHP objects provide a flexible way to organize data and functionality. You can create objects from custom classes, use stdClass for dynamic properties, or convert arrays and scalar values to objects using type casting.

Updated on: 2026-03-15T09:19:28+05:30

33K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements