Created
July 13, 2016 20:54
-
-
Save mphillips/a4e728e62a4b7ab5a993f8fc1106a438 to your computer and use it in GitHub Desktop.
Helper functions to get a property from an array or object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Errthling; | |
/** | |
* Get a property from either an object or an array. | |
* | |
* @param string $key The name of the property to retrieve | |
* @param array|object $data The object to retrieve the property for. | |
* @return mixed | |
*/ | |
function get_property( $key, $data ) { | |
if ( is_array( $data ) ) { | |
return get_array_property( $key, $data ); | |
} elseif ( is_object( $data ) ) { | |
return get_object_property( $key, $data ); | |
} | |
return null; | |
} | |
/** | |
* Get a property from an array. | |
* | |
* @param string $key The name of the property to retrieve | |
* @param array $data The array to retrieve the property for. | |
* @return mixed | |
*/ | |
function get_array_property( $key, $data ) { | |
if ( ! isset( $data[ $key ] ) ) { | |
return null; | |
} | |
return $data[ $key ]; | |
} | |
/** | |
* Get a property from an object. | |
* | |
* @param string $key The name of the property to retrieve | |
* @param object $data The object to retrieve the property for. | |
* @return mixed | |
*/ | |
function get_object_property( $key, $data ) { | |
if ( ! isset( $data->$key ) ) { | |
return null; | |
} | |
return $data->$key; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment