簡體   English   中英

為什么我不能在PHP的類中聲明私有變量?

[英]Why I can't declare a private variable in a class in PHP?

下面的代碼給我一個錯誤:解析錯誤:語法錯誤,意外的T_VARIABLE,期望第4行中的T_FUNCTION

 <?php
  class mydb
  {     
    $mydblink = mysqli_connect( 'localhost:3306','root','123qweasdzxc','test' );         
     public static function checklink() {
        if ( !$mydblink ) {
            die('Could not connect to MySQL: ' . mysql_error()); 
        }
        echo 'Connection OK';
        mysql_close($mydblink);
    }

                  }
  mydb::checklink();

但是將$ mydblink移到該函數中可以使其正常工作,

  <?php
  class mydb
  {     
    public static function checklink() {
        $mydblink = mysqli_connect( 'localhost:3306','root','123qweasdzxc','test' );         

        if ( !$mydblink ) {
            die('Could not connect to MySQL: ' . mysql_error()); 
        }
        echo 'Connection OK';
        mysql_close($mydblink);
    }

  }
  mydb::checklink();

為什么? 這是否意味着我無法在PHP的類中聲明私有變量?

您可以聲明一個私有變量,但不能在類屬性聲明中執行mysql_connect之類的代碼。 您只能設置原語。

class MyDB {
  private $dbc;
  private $someInteger = 4; // you can do this
  private $someArray = array(); // and this.

  public function __construct()
  {
    $this->dbc = new mysqli('localhost', 'user', 'pass', 'db');
  }

  public function getDbc()
  {
    return $this->dbc;
  }

}

$system = new MyDB();
//$system->getDbc()->soSomethingWithMyDb(); 

另外,請注意不建議使用mysql_。 我建議您使用mysqli_或PDO

類中的代碼需要在函數內部:

class mydb{     
    // Parse error
    $mydblink = mysql_connect( 'localhost:3306','root','123qweasdzxc','test' );  
}

class mydb{     
    // Correct
    public function __construct(){
        $this->mydblink = mysql_connect( 'localhost:3306','root','123qweasdzxc','test' );  
    }
}

例如,您需要將其聲明為變量。

private $mydblink = mysql_connect( 'localhost:3306','root','123qweasdzxc','test' );

編輯:這可能是有用的: http : //php.net/manual/en/language.oop5.php

附帶說明mysql_connect需要3個參數,您在此處傳遞了4個

mysql_connect( 'localhost:3306','root','123qweasdzxc','test' );

應該

mysql_connect( 'localhost:3306','root','123qweasdzxc');
mysql_select_db('test');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM