2012-03-20 2 views
1

현재 코드를 향후 업데이트를 위해 잘 구성 할 수 있도록 이전 PHP 스크립트 중 하나를 다시 작성하고 있습니다.파일 include에 PHP 범위 문제가 있습니까?

내가하려는 중 하나는 구성 파일을 만드는 것입니다. 따라서 설정을 하나의 파일을 편집하여 쉽게 변경할 수 있습니다. 파일의

소스 코드 : functions.php

function ConnectToDB() { 

    //database configurations... 
    $host = "localhost"; 
    $dbuser = "root"; 
    $dbpass = ""; 
    $tblname = "parents"; 

    $connection = mysql_connect($host,$dbuser,$dbpass); 

    if (!$connection) { 
     echo 'Could not connect to the database. Please contact the administrator for more information.'; 
    } 

    // select the db 
    $db_selected = mysql_select_db($tblname, $connection); 

    if (!$db_selected) { 
     echo 'Could not select the parents evening table. Please contact the administrator for more information.'; 
     return false; 
    }else{ 
     return true; 
    } 

} 

파일 : config.php를

<?php 

//database configurations... 
$host = "localhost"; 
$dbuser = "root"; 
$dbpass = ""; 
$tblname = "parents"; 

?> 

이 나의 새로운 코드 : 파일 : functions.php

function ConnectToDB() { 

    include('inc/config.php'); 

    global $host; //needed becuase the scope of the variable throws an error otherwise. 
    global $dbuser; //needed becuase the scope of the variable throws an error otherwise. 
    global $dbpass; //needed becuase the scope of the variable throws an error otherwise. 
    global $tblname; //needed becuase the scope of the variable throws an error otherwise. 

    $connection = mysql_connect($host,$dbuser,$dbpass); 

    if (!$connection) { 
     echo 'Could not connect to the database. Please contact the administrator for more information.'; 
    } 

    // select the db 
    $db_selected = mysql_select_db($tblname, $connection); 

    if (!$db_selected) { 
     echo 'Could not select the parents evening table. Please contact the administrator for more information.'; 
     return false; 
    }else{ 
     return true; 
    } 

} 

내 오래된 코드는 완벽하게 작동하지만 이전에는 변수를 다른 파일로 변경했습니다. 계속 출력 "부모 저녁 테이블을 선택할 수 없습니다. 자세한 내용은 관리자에게 문의하십시오. "- 내 응용 프로그램이 데이터베이스에 제대로 연결되어 있지 않음을 의미합니다.

내 코드에 문제가있는 사람이 있습니까? 처음에는 범위 문제라고 생각했지만 내가 여기에 잘못 한 일을 찾을 수 없습니다. 미리

덕분에 어떤 응답을 위해.

답변

2

전역 키워드를 필요가 없습니다합니다. (가) 함수 내 직접 그 변수를 정의하고 있습니다. (가) 포함 된 경우 기능 범위를 벗어난 경우에는 전체 키워드가 필요합니다.

+0

지금 고쳐 주셔서 감사합니다! :) 나는 나 자신을 알아 내지 못해서 어리석은 느낌이 든다. –

+0

문제 없습니다. 다행히 도울 수있어. – dqhendricks

1

잘 모르겠습니다. 설정 파일을 그대로 포함 시키려면 global 키워드가 필요합니다.

그러나 일반적으로 가능한 한 전역 변수를 피하는 것이 좋습니다. Settings 클래스에 설정 매개 변수를 상수로 입력하여 Settings :: host 등을 통해 호출 할 수 있도록하십시오.

전역 변수는 추적하기 어려울 수있는 많은 잠재적 버그를 소개하고 있으므로 문제의 원인이 될 수 있습니다.