Whats new in PHP 8.4
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
php84/libs/LazyObject.php

26 lines
956 B

<?php
class LazyObject {
public function proxy(string $className, mixed $c = null) {
if (!class_exists($className, true)) {
throw new InvalidArgumentException("Class {$className} does not exist");
}
$reflector = new ReflectionClass($className);
if (!$reflector->isInstantiable()) {
throw new InvalidArgumentException("Class {$className} cannot be instantiated");
}
$constructor = $reflector->getConstructor();
// If the class has a constructor with required parameters
if ($constructor && $constructor->getNumberOfRequiredParameters() > 0) {
$initializer = static function (mixed $i) use ($className) {
return new $className($i);
};
return $reflector->newLazyProxy(fn() => $initializer($c));
} else {
$initializer = static function () use ($className) {
return new $className();
};
return $reflector->newLazyProxy($initializer);
}
}
}