is_initialized() 도우미 함수
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;
}
}
당신이 이것을 더 좋게 만들 수 있다고 생각합니까?
이 기능이 더 도움이 될 수 있는 방법에 대한 아이디어가 있으면 알려주십시오.
Reference
이 문제에 관하여(is_initialized() 도우미 함수), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/doekenorg/isinitialized-helper-function-1k4h텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)