클래스 이름이 문자열에 저장된 경우 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
등. 그런 다음 클래스 및 메서드 이름에 대해 데이터베이스에서 반환 한 문자열을 사용하여 코드에서. 상상할 수있는 한 자동화 수준 인 클래스에 대한 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 웹 서비스를 만듭니다.