is_initialized() 도우미 함수

4417 단어 phphelperswebdev
나는 (너무 많은) 전역 도우미 기능의 팬은 아니지만 is_initalized()가 필수라고 생각합니다! 실제로 PHP 네이티브여야 하지만 not happening 입니다.

is_initialized() 헬퍼는 method_exists() 를 본떠 만든 헬퍼로 $object 와 a $property 를 따로 요청한다는 점에서 유사하다. 그 이유는 매개변수가 is_initialized($object->parameter) 와 같이 전달될 때 매개변수의 컨텍스트를 유추할 수 없기 때문입니다. 함수는 값만 받습니다.

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;
        }
    }
}


이것이 isset()보다 나은 이유는 무엇입니까?



그 자체로 "더 나은"것은 아니지만 값이 이제 null 될 수 있으므로 메모이제이션을 더 쉽게 만듭니다. isset()는 이 경우 false를 반환합니다. 사용 사례에 따라 다릅니다.



이 예에서는 메모이제이션에 $service 매개변수를 사용합니다. 매개변수는 null 또는 Service 인스턴스일 수 있습니다. 이 경우 getService() 에 대한 첫 번째 호출만 컨테이너를 호출하는 반면 isset() 값이 null 인 경우 컨테이너를 여러 번 호출합니다.

class Controller
{
    private ?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;
    }
}


당신이 이것을 더 좋게 만들 수 있다고 생각합니까?



이 기능이 더 도움이 될 수 있는 방법에 대한 아이디어가 있으면 알려주십시오.

좋은 웹페이지 즐겨찾기