What is stdClass in PHP?
Last Updated :
01 Aug, 2021
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty.
Uses:
- The stdClass directly access the members by calling them.
- It is useful in dynamic object.
- It is used to set dynamic properties etc.
Program 1: Using array to storing data
<?php
$employee_detail_array = array (
"name" => "John Doe" ,
"position" => "Software Engineer" ,
"address" => "53, nth street, city" ,
"status" => "best"
);
print_r( $employee_detail_array );
?>
|
Output:
Array
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => best
)
Program 2: Using stdClass instead of array to store employee details (dynamic properties)
<?php
$employee_object = new stdClass;
$employee_object ->name = "John Doe" ;
$employee_object ->position = "Software Engineer" ;
$employee_object ->address = "53, nth street, city" ;
$employee_object ->status = "Best" ;
print_r( $employee_object );
?>
|
Output:
stdClass Object
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => Best
)
Note: The type casting of array into object and object to array is possible.
Program 3: Converting array into object
<?php
$employee_detail_array = array (
"name" => "John Doe" ,
"position" => "Software Engineer" ,
"address" => "53, nth street, city" ,
"status" => "best"
);
$employee = (object) $employee_detail_array ;
print_r( $employee );
?>
|
Output:
stdClass Object
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => best
)
Program 4: Converting object properties into array
<?php
$employee_object = new stdClass;
$employee_object ->name = "John Doe" ;
$employee_object ->position = "Software Engineer" ;
$employee_object ->address = "53, nth street, city" ;
$employee_object ->status = "Best" ;
$employee_array = ( array ) $employee_object ;
print_r( $employee_array );
?>
|
Output:
Array
(
[name] => John Doe
[position] => Software Engineer
[address] => 53, nth street, city
[status] => Best
)
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Share your thoughts in the comments
Please Login to comment...