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 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图