-1

下面的代码给了我一个错误:解析错误:语法错误,意外的 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 的类中声明私有变量?

4

4 回答 4

6

你可以声明一个私有变量,但你不能在你的类属性声明中执行 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

于 2013-05-03T07:40:10.160 回答
2

Code in classes needs to be inside a function:

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' );  
    }
}
于 2013-05-03T07:39:35.117 回答
0

You need to declare it as a variable, for example;

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

Edit: this might be useful: http://php.net/manual/en/language.oop5.php

于 2013-05-03T07:37:48.450 回答
0

As a side note mysql_connect requires 3 parameter you passed 4 here

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

should be

mysql_connect( 'localhost:3306','root','123qweasdzxc');
mysql_select_db('test');
于 2013-05-03T07:39:09.940 回答