mysql - Why I can't declare a private variable in a class in PHP? -


the codes below gives me error: parse error: syntax error, unexpected t_variable, expecting t_function in line 4

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

but move $mydblink function makes work,

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

why? mean can't declare private variable in class in php?

you can declare private variable, can not execute code mysql_connect in class property declaration. can set primitives.

class mydb {   private $dbc;   private $someinteger = 4; // can   private $somearray = array(); // , this.    public function __construct()   {     $this->dbc = new mysqli('localhost', 'user', 'pass', 'db');   }    public function getdbc()   {     return $this->dbc;   }  }  $system = new mydb(); //$system->getdbc()->sosomethingwithmydb();  

also, please note mysql_ deprecated. advise use mysqli_ or pdo


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -