D
D
Deric2014-08-08 12:59:16
Laravel
Deric, 2014-08-08 12:59:16

How to properly initialize a multidimensional stdClass object?

Good afternoon.
Dealing with PHP objects, I also came across the possibility of creating dynamic objects using the predefined class stdClass(): I also found the following example of dynamic object initialization:
$std = new stdClass();

$std = new stdClass();
$std->first = 1;
$std->second->third = 3;
print_R($std);
?>
stdClass Object
(
    [first] => 1
    [second] => stdClass Object
        (
            [third] => 3
        )
)

This example demonstrates the ability to create a "multi-dimensional" object, like a corresponding array.
However, trying to use this code within the Laravel 4.1 framework I'm learning always results in an error:
Creating default object from empty value
With reference to an invalid expression:
$std->second->third = 3;
So is it possible to create multidimensional dynamic objects? Or maybe just in Laravel there are some misunderstandings with this kind of object. But if you just create a "one-dimensional" stdClass object, then everything works fine.
Thanks for the help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gillbeits, 2014-08-08
@gillbeits

In fact, you do not get an error, but a Warning, and this is how it should be, because. this breaks the logic of applications and OOP in particular. It is more correct to always set a structure and inherit it, at least in the future, when the moment of code refactoring comes, you can always find the necessary properties and extend them.
And a working example with the error level turned off:

<?php
error_reporting(error_reporting() & ~E_WARNING);
$std = new stdClass();
$std->first = new stdClass();
$std->first->third = 3;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question