Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从基类返回类的实例_Php_Laravel_Class - Fatal编程技术网

Php 从基类返回类的实例

Php 从基类返回类的实例,php,laravel,class,Php,Laravel,Class,我想创建这样一个对象: 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

我想创建这样一个对象:

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
    }
}
因此,我可以实现以下目标:

$obj1 = Obj::find(1);
$obj1->doSomething();
如何创建它,使基类的静态方法返回Obj类的实例


(类似于Laravel处理对象的方式)

在基本模型中,您可以获得调用的子类

例子 $obj的var_转储
查询数据库或使用ORM,有什么问题?
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)
}