Skip to content

Generics via properties instead of parameters #4594

Answered by ondrejmirtes
spud asked this question in Support
Discussion options

You must be logged in to vote

Hi, the easiest solution would be:

/** @template T of object */
class Queryer {
   /** @var class-string<T> */
   private $object_class;
   /** @param class-string<T> $className */
   public function __construct(string $className) {
      $this->object_class = $className;
   }
   public function set_tablename(string $tbl) {
      $this->tablename = $tbl;
   }

   /** @return T|null */
   public function findEntity(int $id) {
      $results = [get record from $this->tablename];
      $class = $this->object_class;
      $obj = new $class($results); 
      return $obj;
   }
}

$q = new Queryer(User::class);
$q->set_tablename('users');
$user = $q->findEntity(23); // knows it's User

Playground…

Replies: 3 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by ondrejmirtes
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@ondrejmirtes
Comment options

@spud
Comment options

@ondrejmirtes
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Support
Labels
None yet
2 participants