1

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

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

If you have >= PHP 5.3...

$class = 'Some' . 'Query';

$query = $class::create();

$query->findPk($id);

Comments

1

Try with:

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

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

Good luck!

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.