sami
sami

Reputation: 155

dynamically constructing this php call

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

SomeQuery::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);

Upvotes: 1

Views: 111

Answers (4)

Catalin Marin
Catalin Marin

Reputation: 1242

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.

Upvotes: 1

Gonzalo Larralde
Gonzalo Larralde

Reputation: 3541

Try with:

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

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

Good luck!

Upvotes: 1

alex
alex

Reputation: 490173

If you have >= PHP 5.3...

$class = 'Some' . 'Query';

$query = $class::create();

$query->findPk($id);

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 400952

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()`**][1] -- 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);

Upvotes: 3

Related Questions