In this lesson we will discuss stdClass instances very briefly. We will get back to them and dig deeper some later.

Simply put, stdClass objects are something like associative arrays. To create an instance of stdClass you should use new operator or cast an associative array to object:

$object1 = new stdClass;
$object2 = (object) [];

You can access or add properties of (to) stdClass with the arrow syntax:

$person = new stdClass;
$person->name = 'Sam';
$person->age = 19;

$car = (object)
    'mark'  => 'Toyota',
    'model' => 'Land Cruiser'

echo 'The mark of the car is ' . $car->mark;

You can access stdClass property indirectly with a name stored in a variable:

$person = new stdClass;
$person->name = 'Sam';
$person->age = 19;

$field = 'name';

echo 'Field ' . $field . ' has value ' . $person->$field; # Prints "Field name has value Sam"

There are some differences between stdClass instances and associative arrays though. We will discuss them some later. We will meet stdClass in further lessons. However this lesson has given you all you need to know about stdClass to go through those further lessons.

Rate this post:
Lesson 14
Lesson 16
Share this page:

Learning plan

Things you should know to configure error reporting properly
How to split PHP script into pieces and include them into each other
14. Operators
We should learn all PHP operators in details before we could continue
15. stdClass
The very basics of stdClass PHP class
16. JSON
How to work with JSON in PHP
17. YAML
How to work with YAML in PHP
Some additional functions you should learn to work with PHP strings