douhui3760 2013-09-06 09:15
浏览 31
已采纳

PHP从__construct返回NULL

I'm trying to write some classes which pull my data out of my database and create objects based on that data. I'm working with CodeIgniter.

The problem is that if an id is supplied to the __construct method but no row in the database table has that id, an object is returned but with all the properties set to NULL.

Is there a way that I can check this and return NULL instead of an object if there is no corresponding row?

class JS_Model extends CI_Model
{
    protected $database_table_name;
    protected $database_keys;
    ...

    public function __construct($id = NULL){
        if($id){
            $this->getFromDatabase($id);
        }
    }

    ...

    function getFromDatabase($id){
        foreach($this->database_keys as $key){
           $this->db->select($key);
        }
        $this->db->from($this->database_table_name);
        $this->db->where('id', $id);
        $this->db->limit(1);
        $q = $this->db->get();

        if ($q->num_rows() > 0){
            foreach($q->result() as $property){     
                foreach($property as $key => $value){
                    $this->$key = $value;
                }
            }
        } else {
            // NEED TO SET THE OBJECT TO NULL FOR THIS CASE
        }
    }

    ...

}

Any help would be appreciated.

  • 写回答

2条回答 默认 最新

  • dongshan7708 2013-09-06 09:20
    关注

    This is not possible, once __construct is called, you will receive an object instance.

    The correct way to handle this is to throw an Exception from inside the constructor.

    class JS_Model extends CI_Model
    {
        protected $database_table_name;
        protected $database_keys;
    
        public function __construct($id = NULL){
            if($id){
                $row = $this->getFromDatabase($id);
                if (!$row) {
                    throw new Exception('requested row not found');
                }
            }
        }
    }
    
    try {
        $record = new JS_Model(1);
    } catch (Exception $e) {
        echo "record could not be found";
    }
    // from here on out, we can safely assume $record holds a valid record
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器