2016-10-12 7 views
-1

私はconnections.phpでmysqli接続を宣言します。私は$ this->接続の代わりにを宣言する$私は1つのファイル内の各機能を分離したいからです。

<?php 
$this->connection = mysqli_connect("localhost","root","","itdforum"); 

     if(mysqli_connect_errno){ 
      echo "Failed to connect to MYSQL: " . mysqli_connect_error(); 
     } 
?>  

私は、誰もがそれを修正する方法を知っている

Using $this when not in object context in localhost\connections.php 

以下のように他の機能

<?php 
include("connections.php"); 
    function getSome(){ 

     $get_some = "SELECT * FROM table" 
     $run_some = mysqli_query($this->connection, $get_some); 
    } 
?> 

が、エラーショーで$この接続を使用しようとしていますか?または私はちょうど1つのPHPファイルにすべての関数を追加しますか?ありがとう。

+0

はmillinonの回答に同意:あなたが使用したい場合は、「$これを」あなたはラッピングを作成する必要がありますクラス。おそらく、それはデータベース全体の相互作用を管理するユーティリティタイプのクラスであろう。 $ GLOBALS ['database']を使用して、接続ポインタを$ thisではなく格納することもできます。 –

答えて

1

クラスをしたいようですね:

class Thing { 
    function __construct(){ 
     $this->connection = mysqli_connect(...) 
     if(mysqli_connect_errno){ 
      echo "Failed to connect to MYSQL: " . mysqli_connect_error(); 
     } 
    } 

    function getSome(){ 
     $get_some = "SELECT * FROM table" 
     $run_some = mysqli_query($this->connection, $get_some); 
    } 

} 

それを使用するには:

include('Thing.php'); 

$thing = new Thing(); 

$thing->getSome(); 
+0

お返事ありがとうございます。追加する場所$ thing = new Thing(); ?それは各機能の内部か外部の機能ですか?ありがとうbtw :) – Rozaimi

+0

'$ thing = new Thing();'はリソース割り当てですので、セットアップが意味を成す場所に置いてください。あなたはたぶんそれを1回しかやりたくないので、おそらく関数の外にあるはずです。 – millinon

関連する問題