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
Post a Comment