Last active
August 1, 2021 13:30
-
-
Save doekenorg/a7c14d5bab8c544964e3e68455c20f3c to your computer and use it in GitHub Desktop.
Helper function for `is_initialized()`
This file contains 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 | |
if (!function_exists('is_initialized')) { | |
/** | |
* Returns whether a property is initialized with a value. | |
* @param string|object $object The class (name), that contains the property. | |
* @param string $property The name of the property. | |
* @return bool Whether the property is initialized with a value. | |
*/ | |
function is_initialized($object, string $property): bool { | |
try { | |
return (new ReflectionProperty($object, $property))->isInitialized(is_object($object) ? $object : null); | |
} catch (ReflectionException $e) { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use this inside a class for memoization.
The object parameter can also be a
string
that references the class name. This is useful for testingstatic
properties.