I'd like to create an object like so:
class Obj extends BaseModel {
public function doSomething() {
// do some stuff with the instance
}
}
class BaseModel {
public static function find($id){
// retrieve object from database and return instance of Obj class
}
}
So i can achieve the following:
$obj1 = Obj::find(1);
$obj1->doSomething();
How can I create this so that the static method from the base class returns an instance of the Obj class?
(similar to how Laravel handles objects)
In your base model, you can get the class of the children that's been called with get_called_class.
class Obj extends Base{
private $id;
public function __construct($id){
$this->id = $id;
}
public function getId(){
return $id;
}
}
class Base{
public static function find($id){
$class = get_called_class();
return new $class($id);
}
}
$obj = Obj::find(1);
object(Obj)#1 (1) {
["id":"Obj":private]=>
int(1)
}