Reputation: 117
I have 3 PHP classes: abstract DBObject, Organization extends DBObject, University extends DBObject.
Loading the objects ends up with an array of data from the DB. Each of the constructors knows how to build itself from that array, so I tried this:
abstract class DBObject {
...
public static function load($id) {
return new self(self::loader($id));
}
}
self::loader($id) properly gets the array. I can make the function load() abstract and copy and paste this code into each child, but I was hoping there was a way to do the above. The current error is:
PHP Fatal error: Cannot instantiate abstract class DBObject in /var/www/htdocs/classes/DBObject.php on line 16
Upvotes: 2
Views: 75
Reputation: 15374
What you're looking for is called late static binding. Instead of self
you want to refer to the class your method is being called from, so switch to the static
keyword:
abstract class DBObject {
...
public static function load($id) {
return new static(static::loader($id));
}
}
Now when called from any sub-class of DBObject the loader function on the sub-class will be called.
Upvotes: 1