What's the best way to instantiate an object as either an instance of a parent class or an instance of a derived class, if you don't know which one to instantiate it as until after you start the instantiation (e.g., because the instantiation depends on data pulled from a database, which is only done during the instantiation within the class constructor)? Example:
class Thing { // parent class
public $thing_type
function __construct($thing_id) {
/* database access code that sets $thing_type as either 'normal' or 'special' */
}
/* Accessor functions, etc. … */
}
class SpecialThing extends Thing { // child class
function __construct($thing_id) {
/* database access code that operates slightly differently that the parent constructor, */
/* but which also sets $thing_type, presumably always as 'special' */
}
}
So I could do:
$thing = new Thing($thing_id);
if ($thing->thing_type == 'special') {
unset($thing);
$thing = new SpecialThing($thing_id);
}
but this seems wasteful because it involves running a whole constructor on an object that is promptly deleted, and involves two database calls instead of one. I was thinking maybe it might be possible to call the child constructor from the parent class somehow, like this (but probably not exactly like this):
class Thing { // parent class
public $thing_type
function __construct($thing_id) {
/* database access code that sets $thing_type */
if ($this->thing_type == 'special') {
$this = new SpecialThing($thing_id);
}
}
/* Accessor functions, etc. … */
}
But that still involves two database calls, even if it would work (not sure, haven't tried it).
There must be a "right" way to do what I want to do--I just don't know what it is.
The closest other stackoverflow question I found was this one, which suggests defining a constructor in the parent class that would take a parent object and copy all the properties into the new object. Then this constructor would be inherited to the child class, enabling creation of a child object by copying an existing parent object. But I'm not sure what this means or how to implement it.
(Using PHP 8.1.5.)