Type
Casting to array
or object
While PHP can cast scalar values implicitly based on the current
context, often casts are also performed explicitly – for instance to
convert an integer
value to a string
. Not
many developers know that PHP, in a somewhat limited way, also
supports the casting of objects to arrays and back:
$obj = new stdClass;
$obj->property = 'hello world';
var_dump((array) $obj);
When executed, the above example will produce the following output:
array(1) {
'property' =>
string(11) "hello world"
}
The output is identical to that of get_object_vars()
with the important difference that a cast is not limited by
visibility, as the following example demonstrates:
class Sample
{
private $property;
public function __construct()
{
$this->property = 'hello world';
}
}
$obj = new Sample;
var_dump((array) $obj);
var_dump(get_object_vars($obj));
array(1) {
'\0Sample\0property' =>
string(11) "hello world"
}
array(0) {
}
Casting an array
to an object
is also
supported, with the hard limitation that only instances of
stdClass
are being created and only public properties
can (easily) be accessed:
$data = [
'property' => 'hello world'
];
$obj = (object) $data;
var_dump($obj->property);
string(11) "hello world"
As names of properties and variables may not be of numeric type
but must be a string, casting an array
with
integer
keys did lead to inaccessible – because
technically invalidly named – properties in earlier versions of PHP.
The behavior has been changed and integer
keys are now
get casted to string for casts from array
to
object
and from string
to
integer
when objects get casted to
array
.
Given that a property named '0'
barely makes sense
and previously was inaccessible, this change of behaviour should not
have any practical impact in a real-world application.