get_property

Get the value assigned to a key

Definition

any get_property(object $object, string $key)

Retrieves the value assigned to $key inside $object. Similar to using the dot accessor as in $object.$key, but allows variables as $key rather than just a static string. Returns null if $key doesn't exist in $object.

Parameters

object $object

Object inside which to look for the property.

string $key

Key inside $object to retrieve value of. Can be the result of an expression, see examples.

Returns

any

The value assigned to $key inside $object.

Examples

{
  "firstName": "Jane",
  "lastName": "Doe",
  "age": 30,
  "status": {
    "Enabled": true
  },
  "roles": [
    "User",
    "Admin"
  ],
  "importantAttribute": "lastName"
}
{
    name: get_property(@, 'firstName'),
    age: get_property(@, 'age'),
    enabled: get_property(get_property(@, 'status'), 'Enabled'),
    last_role: get_property(@, 'roles')[-1],
    lastName: get_property(@, get_property(@, 'importantAttribute')),      // impossible with . accessor
    middleName: get_property(@, 'middleName')
}
{
  "name": "Jane",
  "age": 30,
  "enabled": true,
  "last_role": "Admin",
  "lastName": "Doe",
  "middleName": null
}