By 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
.
#Signature
The signature of the object_get
function is:
1function object_get(
2 $object,
3 $key,
4 $default = null
5);
#Example Use
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// NULL
2$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 );
∎