라이브러리
[PHP] Table::__construct - 테이블 생성자
PHP에서 Table::__construct
PHP에서 `Table::__construct`는 클래스의 생성자 함수로, 클래스의 초기화와 객체의 생성을 담당합니다. 생성자 함수는 클래스의 이름과 동일한 이름으로 정의되며, 객체가 생성될 때 자동으로 호출됩니다.
# 예제 1: 기본적인 Table::__construct
#hostingforum.kr
php
class Table {
private $name;
private $columns;
public function __construct($name, $columns) {
$this->name = $name;
$this->columns = $columns;
}
public function getName() {
return $this->name;
}
public function getColumns() {
return $this->columns;
}
}
$table = new Table('users', ['id', 'name', 'email']);
echo $table->getName() . "
"; // users
echo implode(', ', $table->getColumns()) . "
"; // id, name, email
# 예제 2: 생성자 함수에서 데이터베이스 연결 설정
#hostingforum.kr
php
class Table {
private $name;
private $columns;
private $db;
public function __construct($name, $columns, $host, $username, $password, $database) {
$this->name = $name;
$this->columns = $columns;
$this->db = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
public function getName() {
return $this->name;
}
public function getColumns() {
return $this->columns;
}
public function select() {
$stmt = $this->db->prepare("SELECT * FROM $this->name");
$stmt->execute();
return $stmt->fetchAll();
}
}
$table = new Table('users', ['id', 'name', 'email'], 'localhost', 'root', 'password', 'mydatabase');
$result = $table->select();
print_r($result);
# 예제 3: 생성자 함수에서 초기화 메소드 호출
#hostingforum.kr
php
class Table {
private $name;
private $columns;
private $initialized;
public function __construct($name, $columns) {
$this->name = $name;
$this->columns = $columns;
$this->initialized = false;
$this->init();
}
private function init() {
// 초기화 로직
echo "Table $this->name initialized
";
$this->initialized = true;
}
public function getName() {
return $this->name;
}
public function getColumns() {
return $this->columns;
}
public function isInitialized() {
return $this->initialized;
}
}
$table = new Table('users', ['id', 'name', 'email']);
echo $table->getName() . "
"; // users
echo implode(', ', $table->getColumns()) . "
"; // id, name, email
echo ($table->isInitialized() ? 'true' : 'false') . "
"; // true
위 예제에서 `Table::__construct`는 클래스의 초기화와 객체의 생성을 담당합니다. 생성자 함수는 클래스의 이름과 동일한 이름으로 정의되며, 객체가 생성될 때 자동으로 호출됩니다. 생성자 함수에서 데이터베이스 연결 설정, 초기화 메소드 호출 등 다양한 로직을 처리할 수 있습니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.