(PHP 8 >= 8.4.0)
ReflectionClass::markLazyObjectAsInitialized — 将惰性对象标记为已初始化,而不调用初始化器或工厂
将惰性对象标记为已初始化,而不调用初始化器或工厂。如果object
不是惰性对象或已初始化,则此方法无效。
调用此方法的效果与初始化序列中描述的幽灵对象(无论object
的惰性策略如何)相同,只是不调用初始化器。之后,该对象与从未是惰性对象且使用ReflectionClass::newInstanceWithoutConstructor()创建的对象无法区分,除了使用ReflectionProperty::setRawValueWithoutLazyInitialization()或ReflectionProperty::skipLazyInitialization()已初始化的属性的值。
object
返回object
。
示例 #1 将未初始化的惰性对象标记为已初始化
<?php
class Example
{
public string $prop1;
public string $prop2;
public string $prop3 = 'default value';
}
$reflector = new ReflectionClass(Example::class);
$object = $reflector->newLazyGhost(function ($object) {
echo "Initializer called\n";
$object->prop1 = 'initialized';
});
$reflector->getProperty('prop1')
->setRawValueWithoutLazyInitialization($object, 'prop1 value');
var_dump($object);
$reflector->markLazyObjectAsInitialized($object);
var_dump($object);
?>
以上示例将输出
lazy ghost object(Example)#3 (1) { ["prop1"]=> string(11) "prop1 value" ["prop2"]=> uninitialized(string) ["prop3"]=> uninitialized(string) } object(Example)#3 (2) { ["prop1"]=> string(11) "prop1 value" ["prop2"]=> uninitialized(string) ["prop3"]=> string(13) "default value" }
示例 #2 将已初始化的对象标记为已初始化
<?php
class Example
{
public string $prop1;
public string $prop2;
public string $prop3 = 'default value';
}
$reflector = new ReflectionClass(Example::class);
$object = $reflector->newLazyGhost(function ($object) {
echo "Initializer called\n";
$object->prop1 = 'initialized';
});
$reflector->getProperty('prop1')
->setRawValueWithoutLazyInitialization($object, 'prop1 value');
var_dump($object->prop3);
var_dump($object);
$reflector->markLazyObjectAsInitialized($object);
var_dump($object);
?>
以上示例将输出
Initializer called string(13) "default value" object(Example)#3 (2) { ["prop1"]=> string(11) "initialized" ["prop2"]=> uninitialized(string) ["prop3"]=> string(13) "default value" } object(Example)#3 (2) { ["prop1"]=> string(11) "initialized" ["prop2"]=> uninitialized(string) ["prop3"]=> string(13) "default value" }