April 15, 2018 —John Koster
The object_get
allows developers to retrieve properties from a given $object
using dot notation. This is useful in situations where it can not be guaranteed that a provided object will have a given property, identified by the given $key
.
The signature of the object_get
function is:
1function object_get(2 $object,3 $key,4 $default = null5);
The following sample class structure will be used in the following examples:
1$sampleObject = new stdClass;2$sampleObject->department = new stdClass;3 4$sampleObject->department->name = 'Marketing';
The department name can be retrieved like so:
1$departmentName = object_get(2 $sampleObject,3 'department.name'4 );
The value of $departmentName
would then be Marketing
.
Attempting to retrieve the department's address would return NULL
:
1// NULL2$departmentAddress = object_get(3 $sampleObject,4 'department.address'5 );
Or a different $default
value can be supplied:
1// `No Address`2$departmentAddress = object_get(3 $sampleObject,4 'department.address',5 'No Address'6 );
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.