source

PHP는 클래스 이름에서 개체를 문자열로 인스턴스화할 수 있습니까?

factcode 2022. 9. 28. 00:06
반응형

PHP는 클래스 이름에서 개체를 문자열로 인스턴스화할 수 있습니까?

클래스 이름이 문자열에 저장되어 있는 경우 클래스 이름에서 개체를 인스턴스화하는 것이 PHP에서 가능한가요?

네, 물론입니다.

$className = 'MyClass';
$object = new $className; 

, 그렇습니다.

<?php

$type = 'cc';
$obj = new $type; // outputs "hi!"

class cc {
    function __construct() {
        echo 'hi!';
    }
}

?>

클래스에 인수가 필요한 경우 다음을 수행해야 합니다.

class Foo 
{
   public function __construct($bar)
   {
      echo $bar; 
   }
}

$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));

스태틱도:

$class = 'foo';
return $class::getId();

데이터베이스와 같은 저장소에 클래스 이름 / 메서드를 저장하여 동적 호출을 수행할 수 있습니다.클래스가 오류에 대해 복원력이 있다고 가정합니다.

sample table my_table
    classNameCol |  methodNameCol | dynamic_sql
    class1 | method1 |  'select * tablex where .... '
    class1 | method2  |  'select * complex_query where .... '
    class2 | method1  |  empty use default implementation

etc. 그런 다음 클래스와 메서드 이름에 대해 데이터베이스에서 반환된 문자열을 사용하여 코드에서 입력합니다.클래스에 대한 SQL 쿼리를 저장할 수도 있습니다.상상에 따라 자동화 수준도 지정할 수 있습니다.

$myRecordSet  = $wpdb->get_results('select * from my my_table')

if ($myRecordSet) {
 foreach ($myRecordSet   as $currentRecord) {
   $obj =  new $currentRecord->classNameCol;
   $obj->sql_txt = $currentRecord->dynamic_sql;
   $obj->{currentRecord->methodNameCol}();
}
}

이 방법을 사용하여 REST 웹 서비스를 만듭니다.

언급URL : https://stackoverflow.com/questions/1377052/can-php-instantiate-an-object-from-the-name-of-the-class-as-a-string

반응형