Tuesday, March 21, 2023

How to create a dynamic object from standard class

 PHP provides a class to create a temporary object where no specific class and members are required.


The class stdClass is the empty class in PHP used to cast other types to object. Among the example of stdClass usage;

  1. Directly access the members by calling them
  2. Dynamic objects can be provided for temporary usage
E.g. 
An array can be treated as an object by using stdClass. 

$tmpStudent = array(
"name" => "John Doe"
);

To access data, 
$tmpStudent['name']

$tmpStudent = new stdClass;
$tmpStudent->name = "John Doe";

Using the stdClass, this can be done as an object
$tmpStudent->name


No comments:

Blog Archive