programing

PHP에서 call_user_func_array를 사용하여 생성자를 호출하는 방법

lovejava 2023. 7. 23. 13:53

PHP에서 call_user_func_array를 사용하여 생성자를 호출하는 방법

call_user_func_array를 사용하는 클래스의 생성자를 어떻게 호출할 수 있습니까?

다음 작업을 수행할 수 없습니다.

$obj = new $class();
call_user_func_array(array($obj, '__construct'), $args); 

생성자에 매개 변수가 있으면 새 매개 변수가 실패하기 때문입니다.

제약 조건: 인스턴스화해야 하는 클래스를 제어하지 않으며 수정할 수도 없습니다.

제가 왜 이런 미친 짓을 하고 싶은지 묻지 마세요. 이건 미친 시험입니다.

반사는 다음과 같이 사용할 수 있습니다.

$reflect  = new ReflectionClass($class);
$instance = $reflect->newInstanceArgs($args);

PHP 5.6.0부터는 연산자도 이 목적으로 사용할 수 있습니다.

$instance = new $class(...$args);

if(version_compare(PHP_VERSION, '5.6.0', '>=')){
    $instance = new $class(...$args);
} else {
    $reflect  = new ReflectionClass($class);
    $instance = $reflect->newInstanceArgs($args);
}

언급URL : https://stackoverflow.com/questions/2409237/how-to-call-the-constructor-with-call-user-func-array-in-php