2016-07-21 3 views
-3

필자는 프로그래밍 경험이별로 없지만 몇 가지 PHP 파일로 약간의 응용 프로그램을 작성 했으므로이를 최적화하고 싶습니다.PHP. 어떻게 함수의 라이브러리를 만들 수 있습니까?

반복 코드를 모두 추출하여 PHP 파일로 폴더에 넣고 싶습니다. 코드가 필요할 때 나중에 호출합니다.

는 예를 들어,이 라인은 내 모든 파일에 반복 : 모든

$servername = "ejemplo.es"; 
$username = "ramon"; 
$dbname = "bbdd"; 
$password = "loquesea"; 

$conn = new mysqli($servername, $username, $password, $dbname); 
if ($conn->connect_error) { 
     die("Connection failed: " . $conn->connect_error); 
} 
+0

그 코드를 별도의 파일에 넣고 필요할 경우 [include] (http://php.net/manual/en/function.include.php) 할 수 있습니다. – showdev

+0

@showdev a require_once는 특히 데이터베이스 연결을 포함하는 경우'include'보다 더 적합 할 것입니다 : http://stackoverflow.com/questions/2418473/difference-between-require-include-and-include -once – ILikeTacos

+0

@showdev 클래스를 만들거나 간단한 함수로 작성 하시겠습니까? (포함 된 파일에) –

답변

3

첫째, 당신은 PHP 튜토리얼에 대한 functionsobject orientated programming을 읽어야합니다.

귀하의 경우에는

, 당신은 다음과 같이 보일 것이다, 데이터베이스라는 데이터베이스 것들에 대한 클래스를 가질 수있다 : 다음

<?php 

class Database 
{ 
    private $_connection = null; 

    public function __construct($host, $username, $password, $database) 
    { 
     // connect to database and store the connection for further use 
    } 

    public function doThisAndThat() 
    { 
     // do some fancy database stuff 
    } 

    public function __destruct() 
    { 
     // important for databases is to disconnect from them 
    } 
} 

을 당신이 당신의 데이터베이스 클래스 파일을 포함하고 같이 호출하기 만하면됩니다 그 :

$db = new Database($host, $username, $password, $database); 
$db->doThisAndThat(); 
+0

그 덕분에, 고마워요. –

관련 문제