저는 OOP를 처음 접했고 빠른 질문이 있습니다.
내 코드에는 다음과 같은 클래스가 있습니다.
Class DB {
//contains all my mysqli stuff
}
Class A {
All functions within this class will need a db connection
}
모든 함수에서 새 DB 인스턴스를 생성 할 필요없이 클래스 내에서 연결을 생성하려면 어떻게해야합니까?
이것이 가능할까요?
미리 감사드립니다.
의 경우 class DB
DB 연결 (예 : 열기 및 닫기)을 설정할 수 있습니다. 를 사용하여 class A
의 메서드를 상속하도록 클래스를 설정할 수 있습니다 . 외부에서 클래스에 액세스 할 필요가 없기 때문에 모든 메서드가 기본적으로 PHP에 있으므로 메서드 (절차 적 함수) 를 로 변경했습니다 .class DB
extends
class DB
protected
public
또한 생성자 (주석에서 언급했듯이) 사용을 추가 하여 객체가 .NET에서 생성 될 때 DB 연결이 자동으로 열립니다 Class A
. 개인적으로 저는 생성자에서 DB 연결을 열지 않을 것이지만 편집증에 불과합니다. 의심스러운 경우 방법에서 연결을 닫으십시오.
<?php
Class DB {
protected function conDB() { //Protected can only be accessed by same class or inherited class
echo "Open connection to DB";
}
protected function closeDB() { //Protected can only be accessed by same class or inherited class
echo "Connection Closed";
}
}
Class A extends DB { //Extends will use all methods from inherited class
function __construct() { //Constructer will run on Object creation and open connection to DB
$this->conDB();
}
public function selectDB() {
echo "<br>";
echo "Data Select Here!";
echo "<br>";
$this->closeDB(); //You will still need to close the DB Connection
}
}
클래스 A에서 개체 만들기
$select = new A(); //Create Object
$select->selectDB();
클래스 A를 호출하는 출력
Open connection to DB
Data Select Here!
Connection Closed
읽을 거리:
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다