저는 이와 같이 동적으로 호출하려고합니다. 당신이 PHP를 사용하는 경우가이 PHP 호출을 동적으로 생성합니다.
$dynamic = "Some";
$tablename = $dynamic."Query::create()";
$$tablename->findPk($id);
저는 이와 같이 동적으로 호출하려고합니다. 당신이 PHP를 사용하는 경우가이 PHP 호출을 동적으로 생성합니다.
$dynamic = "Some";
$tablename = $dynamic."Query::create()";
$$tablename->findPk($id);
를 작동하지 않는 이유를 변경 유일한 부분은
SomeQuery::create->findPk($id);
Some
은 그래서
WhatQuery::create->findPk($id);
OtherQuery::create->findPk($id);
나는이 시도,하지만 확신 할 수있다 > = 5.3이면 다음을 사용할 수 있습니다.
$className = 'SomeQuery'; // or another one
$className::create()->findPk($id);
참조 용 페이지 : Scope Resolution Operator
그러나 PHP는 < 5.3에는 유효하지 않습니다.
PHP 5.2를 사용하면 call_user_func()
또는 familly의 다른 기능을 기반으로 한 솔루션으로 대체해야합니다.
$tablename = $dynamic."Query::create";
그리고 만약 : 당신이> = PHP 5.3 ...
$class = 'Some' . 'Query';
$query = $class::create();
$query->findPk($id);
:
나는 이런 식으로 뭔가 트릭을 할해야 가정 작동하지 않으면 call_user_func을 array($dynamic."Query", "create")
과 함께 사용하십시오.
행운을 빈다.
과 함께 시도하는 경우
$className = 'SomeQuery'; // or another one
$created = call_user_func(array($className, 'create'));
$created->findPk($id);
공장 패턴이 사용되는 :
class QueryCreator {
public static function create($queryTypeName) {
if(class_exists($queryTypeName)) {
return $queryTypeName::create();// to use your model.
// I'd use return new $queryTypeName();
}else {
throw Exception("class ".$queryTypeName." does not exist");
}
}
}
사용 :
try {
$query = QueryCreator::create("myQuery");
$query->findPK($id);
} catch (Exception $e) {
// whatever// throw it forward or whatever you want to do with it;
}
하는 조회 유형이 동일한 인터페이스를 구현합니다 있는지 확인합니다. 그렇지 않으면 오류가 발생할 수 있습니다.
위대한 마음? :) +1 – alex