Automattic\WooCommerce\Internal\DependencyManagement
RuntimeContainer::instantiate_class_using_reflection
Get an instance of a class using reflection. This method recursively calls 'get_core' (which in turn calls this method) for each of the arguments in the 'init' method of the resolved class (if the method is public and non-static).
Method of the class: RuntimeContainer{}
No Hooks.
Returns
Object. The resolved object.
Usage
// private - for code of main (parent) class only $result = $this->instantiate_class_using_reflection( $class_name, $resolve_chain ): object;
- $class_name(string) (required)
- The name of the class to resolve.
- $resolve_chain(array) (required)
- Classes already resolved in this resolution chain. Passed between recursive calls to the method in order to detect a recursive resolution condition.
RuntimeContainer::instantiate_class_using_reflection() RuntimeContainer::instantiate class using reflection code WC 10.6.2
private function instantiate_class_using_reflection( string $class_name, array &$resolve_chain ): object {
$ref_class = new \ReflectionClass( $class_name );
// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped
$constructor = $ref_class->getConstructor();
if ( ! is_null( $constructor ) ) {
if ( ! $constructor->isPublic() ) {
throw new ContainerException( "Error resolving '$class_name': the class doesn't have a public constructor." );
}
$constructor_arguments = $constructor->getParameters();
foreach ( $constructor_arguments as $argument ) {
if ( ! $argument->isOptional() ) {
throw new ContainerException( "Error resolving '$class_name': the class constructor has non-optional arguments." );
}
}
}
$instance = $ref_class->newInstance();
if ( ! $ref_class->hasMethod( 'init' ) ) {
return $instance;
}
$init_method = $ref_class->getMethod( 'init' );
if ( ! $init_method->isPublic() || $init_method->isStatic() ) {
return $instance;
}
$init_args = $init_method->getParameters();
$init_arg_instances = array_map(
function ( \ReflectionParameter $arg ) use ( $class_name, &$resolve_chain ) {
$arg_type = $arg->getType();
if ( ! ( $arg_type instanceof \ReflectionNamedType ) ) {
throw new ContainerException( "Error resolving '$class_name': argument '\${$arg->getName()}' doesn't have a type declaration." );
}
if ( $arg_type->isBuiltin() ) {
throw new ContainerException( "Error resolving '$class_name': argument '\${$arg->getName()}' is not of a class type." );
}
if ( $arg->isPassedByReference() ) {
throw new ContainerException( "Error resolving '$class_name': argument '\${$arg->getName()}' is passed by reference." );
}
return $this->get_core( $arg_type->getName(), $resolve_chain );
},
$init_args
);
// phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped
$init_method->invoke( $instance, ...$init_arg_instances );
return $instance;
}