질문 Q #22252
ci4 DB인스턴스 초기화 관련해서
마로3 2020-03-20 13:21:18

안녕하세요 프로그램 작성하다 궁금한점 있어서 여쭤 봅니다.

아래에서 DB인스턴스 초기화를 2가지 방법으로 해 놓았습니다.

생성자에서 초기화, 메서드에서 초기화 .. 이렇게 두가지 방법에 대해....

생성자 초기화시에는 딸린 메서드들이 전부 안나오는듯하여 혹시 둘의 차이가 있을까 하여 여쭙니다. 

답변주시는 분들 항상 감사 드립니다.

 

class Book_model extends Model {

      protected $db;

      public function __construct(){ 

             $this->db = \Config\Database::connect();

      }

     public function insertTable() {

       $db = \Config\Database::connect();

     }

}

답변 3
#1 한대승(불의회상) 2020-03-20 13:39:47

에디터에서 인식하는 방법의 차이입니다.

객체 자체는 변함 없습니다.

#2 마로3 2020-03-20 13:46:54
네 저도 그렇게 생각하는데요.. 실제 생성자에서 초기화시에 .. 예를들어 $this->db->affectedraws() , getError 등의 메서드가 안먹고 에러가 나더라구요.. 
#3 변종원(웅파) 2020-03-20 14:10:57
<?php namespace App\Models;

use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
use CodeIgniter\Validation\ValidationInterface;

class UserModel extends Model
{
   protected $table = 'users';

   function __construct(ConnectionInterface &$db = null, ValidationInterface $validation = null)
   {
      parent::__construct($db, $validation);

      $this->db = \Config\Database::connect();
   }

}

잘 작동됩니다..