2016-12-19 1 views
0

私はグローバル$connectionのクラスを持っていますが、私はそれにアクセスしようとするとNULLになっています。あなたがコンストラクタ内でアクセスしようとするとわかるように、私はNULLを取得しません。しかし、getConnection()から私はNULLを取得しています。接続を開始しようとすると、なぜNULLになるのですか?

class DatabaseManipulation 
{ 
    private $connection; 

    function __construct() 
    { 
     global $connection; 
     $connection = new mysqli("localhost", "root", "", "db"); 
     $result = $connection->query("select * from user"); 

     print_r($result); //I get an array 
    } 

    function getConnection(){ 
     global $connection; 
     var_dump($connection); // I get -> object(DatabaseManipulation)#1 (1) { ["connection":"DatabaseManipulation":private]=> NULL } NULL 
    } 

} 

オブジェクトをインスタンス化するときと同じことが起こります。$connection = new DatabaseManipulation();。私は何か間違っているのですか?私はこれがOOのやり方で行われることを望みます。誰でも助けてくれますか?

答えて

1

OO PHPは手続き型ではありません。私は、これはオブジェクト指向の方法で行うことにしたい

$this->connection = new mysqli("localhost", "root", "", "db");; 
1

:だから、それを変更します。

globalを使用して停止します。あなたがクラスにいるときにグローバル状態を参照したくない。 The Basicsを見てみると、オブジェクト内に擬似変数$thisがあることがわかります。

class DatabaseManipulation 
{ 
    private $connection; 

    function __construct() 
    { 
     $this->connection = new mysqli("localhost", "root", "", "db"); 
    } 

    function getConnection(){ 
     var_dump($this->connection); 
    } 
} 

それについての詳細:

  1. Why is Global State so Evil?
  2. What does the variable $this mean in PHP?
+0

私はまだエラーが取得しています:注意:未定義の変数を:で接続.... –

+0

どこコードですか? '$ this-> connection-> query(" select * from user ");' – Federkun

+0

ここを見てみよう - > http://pastebin.com/DCvXLkiT –

関連する問題