大家好好避开PHP上的东西已经有一段时间了,但是我试图获取一个coreDB.php文件来获取数据库信息并从这个文件中打开和关闭。
一切正常,但当我尝试将其包含在另一个文件中时,我总是得到我在标题上的错误。
coreDB文件:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
class ConnectionDB
{
private $dbhost = "localhost";
private $dbuser = "user";
private $dbpass = "password";
private $dbname = "dbname";
public $conn;
public function openDbConnection()
{
try
{
$this->conn = new PDO("mysql:host=$this->dbhost;dbname=$this->dbname", $this->dbuser, $this->dbpass);
echo "Connection Done<br>";
}
catch(PDOException $e)
{
//var_dump($this->conn);
//echo $e->getMessage();
}
}
public function closeDbConnection()
{
try
{
$this->conn = NULL;
echo "Connection Over";
}
catch(PDOException $e)
{
//var_dump($this->conn);
//echo $e->getMessage();
}
}
}?>
另一个文件clientNewRecord.php,其中包含前者:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include("coreDB.php");
echo "this is a test";
private $dbConnect = new ConnectionDB();
$this->dbConnect->openDbConnection();
$this->dbConnect->closeDbConnection();?>
我总是得到这个错误:PHP Parse错误:语法错误,尝试打开clientNewRecord.php时意外'私有'
当我尝试运行$ this-&gt; dbConnect-&gt; openDbConnection()时,是否进入该文件并从该文件运行?
答案 0 :(得分:3)
将private $dbConnect = new ConnectionDB();
更改为$dbConnect = new ConnectionDB();
。只允许在类中使用访问说明符。
答案 1 :(得分:1)
正如apokryfos所提到的,你不能对不属于类属性的变量声明访问(public
,private
,protected
)(或者单独在类函数声明上)
所以你会这么做:
$dbConnect = new ConnectionDB();
$dbConnect->openDbConnection();
$dbConnect->closeDbConnection();