2014-02-09 98 views
-1

我想在其他函數中調用$con變量。這個變量包含我的數據庫連接,所以一些查詢在我的其他函數中運行,所以我需要在其他函數中調用這個$con變量。也許我的概念不好。但請建議加上給我解決方案。在其他函數中調用變量

PHP

Class CORE 
{ 


     public function connect_database() 

     { 


     $connection=mysqli_connect(host,user,"1234"); 

     $con = mysqli_select_db($connection,database); 
     if (mysqli_connect_errno($con)) 
     { 
     echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
     } 

    } 

     public function show_name() 
     { 

     $user = base64_decode($_SESSION['admin']); 
     $query = mysqli_query($con,"SELECT full_name FROM admin_user WHERE user='".$user."'"); 

     while($row = mysqli_fetch_array($query)) 
     { 
      echo $row['full_name']; 
     } 


     } 



} 

回答

0

更改類小:

Class CORE { 

    protected $con; 
    public $error; 


    public function get_con(){ 
     return $this->con; 
    } 

    public function connect_database(){ 

     connection=mysqli_connect(host,user,"1234"); 

     $this->con = mysqli_select_db($connection,database); 
     if (mysqli_connect_errno($this->con)){ 
     $this->error = mysqli_connect_error(); 
     } 

    } 

    public function show_name(){ 

    $user = base64_decode($_SESSION['admin']); 
    $query = mysqli_query($this->con,"SELECT full_name FROM admin_user WHERE  
    user='".$user."'"); 
    while($row = mysqli_fetch_array($query)) {echo $row['full_name'];} 
    } 
} 

現在創建類的實例來檢查$con$error

$test = new CORE(); 
echo $test->get_con(); 
echo $test->error; 

如果$con給ñ o錯誤(並且$error顯示沒有錯誤)通過$this->con

將其用於任何其他功能