Skip to content

Instantly share code, notes, and snippets.

@doekenorg
Last active August 1, 2021 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doekenorg/a7c14d5bab8c544964e3e68455c20f3c to your computer and use it in GitHub Desktop.
Save doekenorg/a7c14d5bab8c544964e3e68455c20f3c to your computer and use it in GitHub Desktop.
Helper function for `is_initialized()`
<?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;
}
}
}
@doekenorg
Copy link
Author

doekenorg commented Aug 1, 2021

You can use this inside a class for memoization.

class Controller
{
    public ?Service $service;

    public function getService(): ?Service
    {
        if (!is_initialized($this, 'service')) {
            $this->service = Container::get(Service::class); // either the service, or `null`
        }
        
        return $this->service;
    }
}

The object parameter can also be a string that references the class name. This is useful for testing static properties.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment