我第一次在PHP中使用类做了一些事情.我想return object array在课堂上取一件物品.
这是我的班级
class User {
$dbconn = include("config.php");
private $dbHost = $dbconn->host;
private $dbUsername = $dbconn->username;
private $dbPassword = $dbconn->pass;
private $dbName = $dbconn->database;
private $userTbl = 'users';
function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的config.php档案
return (object) array(
'host' => 'localhost',
'username' => 'my_user',
'pass' => 'my_pass',
'database' => 'my_db'
);
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
PHP Parse error: syntax error, unexpected '$dbconn' (T_VARIABLE)
Run Code Online (Sandbox Code Playgroud)
您不能在变量定义中使用可执行代码,只能使用静态值.所以不支持这种事情:
class foo {
public $var = result_of_some_function();
}
Run Code Online (Sandbox Code Playgroud)
如果要初始化值,请使用构造函数.您可能最好将其作为配置文件阅读:
class User {
public function __construct() {
$config = json_decode(file_get_contents('config.json'));
$conn = new mysqli($config->host, ...);
}
}
Run Code Online (Sandbox Code Playgroud)
或者更好,使用依赖注入:
class User {
protected $db = null;
public function __construct($db) {
$this->db = $db;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的代码中创建一个用户对象:
$db = new Db($config);
$user = new User($db);
Run Code Online (Sandbox Code Playgroud)