我第一次使用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;
}
}
}
}
这是我的config.php
文件
return (object) array(
'host' => 'localhost',
'username' => 'my_user',
'pass' => 'my_pass',
'database' => 'my_db'
);
我该怎么做?
PHP Parse error: syntax error, unexpected '$dbconn' (T_VARIABLE)
答案 0 :(得分:5)
您不能在变量定义中使用可执行代码,只能使用静态值。所以不支持这种事情:
class foo {
public $var = result_of_some_function();
}
如果要初始化值,请使用构造函数。你可能最好把它作为配置文件阅读:
class User {
public function __construct() {
$config = json_decode(file_get_contents('config.json'));
$conn = new mysqli($config->host, ...);
}
}
或者更好,使用依赖注入:
class User {
protected $db = null;
public function __construct($db) {
$this->db = $db;
}
}
然后在创建用户对象的代码中:
$db = new Db($config);
$user = new User($db);
答案 1 :(得分:3)
另一种方法是在配置文件中定义常量并在类中使用它们。
在config.php文件中
define('HOST', 'localhost');
define('USERNAME', 'my_user');
define('PASS', 'my_pass');
define('DATABASE', 'my_db');
在课程文件
中include("config.php")
class User {
private $dbHost = HOST;
private $dbUsername = USERNAME;
private $dbPassword = PASS;
private $dbName = 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;
}
}
}
}
答案 2 :(得分:2)
包括这个:
$dbconn = include("config.php");
在你的构造函数中。
答案 3 :(得分:2)
也许您应该将代码更改为
function __construct()
{
//included db file
include 'config.php';
if (!isset($this->db))
{
//code here
}
答案 4 :(得分:1)
尝试这种方式使用它。
<?php
class User
{
private $dbconn = null;
private $dbHost;
private $dbUsername;
private $dbPassword;
private $dbName;
private $userTbl = 'users';
function __construct()
{
include 'config.php'; //included file in constructor
if (!isset($this->db))
{
$this->dbHost= $this->dbconn->host;
$this->dbUsername= $this->dbconn->username;
$this->dbPassword= $this->dbconn->pass;
$this->dbName= $this->dbconn->database;
// 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;
}
}
}
}
<强> CONFIG.PHP 强>
<?php
$this->dbconn= (object) array(
'host' => 'localhost',
'username' => 'my_user',
'pass' => 'my_pass',
'database' => 'my_db'
);