Im starting to move away from using arrays in PHP as objects are so much neater and in php 5 there is no performance hits when using objects.
Currently the way I do it is:
$object = (object) array('this' => 'that', 'foo' => (object) array('bar' => 123));
However, i find it so tedious to have to typecast every time as typecasting isnt recursive...
Is there any way in php (or will there be) to do it like this or something similar:
$object = {
'this' => 'that',
'foo' => {
'bar' => 123
}
};
PHP is something called an object-oriented programming language, which means that objects containing multiple different properties can be created.
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.
Using new stdClass() to create an object without class: For creating an object without a class, we will use a new stdClass() operator and then add some properties to them. Syntax: // Creating an object $object = new stdClass(); // Property added to the object $object->property = 'Property_value';
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.
Starting from PHP 5.4 short array syntax has become available. This allows you to initialize array like this:
$myArray = ["propertyA" => 1, "propertyB" => 2];
There is no currently short object syntax in PHP as of PHP7. But you can cast short array syntax to create objects like this:
$myObject = (object) ["propertyA" => 1, "propertyB" => 2];
Looks much nicer and shorter than using the following construct:
$myObject = new \StdClass();
$myObject->propertyA = 1;
$myObject->propertyB = 2;
I have an alternative solution for when you receive an already built array. Say your array has n nested arrays so you have no chance of casting each one in a simple way. This would do the trick:
$object = json_decode(json_encode($unknownArray));
I would not use this in a large loop or something similar, as it is way slower than just sticking with the array sintax and live with it. Also, if an element of the array is a function or some other funny thing this would break that.
Example usage:
$unknownArray = array(
'a' => '1',
'b' => '2',
'c' => '3',
'd' => array(
'x' => '7',
'y' => '8',
'z' => '9',
),
);
$object = json_decode(json_encode($unknownArray));
echo $object->d->x;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With