PHP Conference Japan 2024

ReflectionClass::markLazyObjectAsInitialized

(PHP 8 >= 8.4.0)

ReflectionClass::markLazyObjectAsInitialized将惰性对象标记为已初始化,而不调用初始化器或工厂

描述

public ReflectionClass::markLazyObjectAsInitialized(object $object): object

将惰性对象标记为已初始化,而不调用初始化器或工厂。如果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"
}

参见

添加注释

用户贡献的注释

此页面没有用户贡献的注释。
To Top