开发者

dynamically constructing this php call

I'm trying to dynamically construct a call like this. The only part that changes is Some

S开发者_开发技巧omeQuery::create->findPk($id);

so it could be

WhatQuery::create->findPk($id);
OtherQuery::create->findPk($id);

I tried this, but not sure why it isn't working

$dynamic = "Some";
$tablename = $dynamic."Query::create()";
$$tablename->findPk($id);


If you are using PHP >= 5.3, you can use the following :

$className = 'SomeQuery';  // or another one
$className::create()->findPk($id);

As a reference, see this page of the manual : Scope Resolution Operator

But that's not valid for PHP < 5.3.


With PHP 5.2, you'll have to fallback to a solution based on call_user_func() -- or another function of its familly.

I suppose something like this should do the trick :

$className = 'SomeQuery';  // or another one
$created = call_user_func(array($className, 'create'));
$created->findPk($id);


If you have >= PHP 5.3...

$class = 'Some' . 'Query';

$query = $class::create();

$query->findPk($id);


Try with:

$tablename = $dynamic."Query::create";

And if it doesn't work, use call_user_func with array($dynamic."Query", "create").

Good luck!


Factory pattern to be used:

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");
         }
   }
}

usage:

  try {
    $query = QueryCreator::create("myQuery");
    $query->findPK($id);

  }  catch (Exception $e) {
     // whatever// throw it forward or whatever you want to do with it;
  }

Make sure that your Query types objects implement the same interface. otherwise you can get errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜