class / dbConnect.php page
class dbConnect {
/*
* initiate mysql database host,username,password,database name
*/
private $host;
private $dbName;
private $uname;
private $upass;
private $con;
public function __construct($host, $database, $userName, $password) {
$this->host = $host;
$this->dbName = $database;
$this->uname = $userName;
$this->upass = $password;
$this->connectDB();
}
public function connectDB() {
/*
* @var $dsn mean data source name for pdo connection
*/
$dsn = "mysql:host=" . $this->host . ";dbName=" . $this->dbName;
try {
$this->con = new PDO($dsn, $this->uname, $this->upass);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
class/sampleView.php
/*
* include dbConnect class for this SampleView Class Page
*/
require_once './dbConnect.php';
class sampleViews extends dbConnect{
function viewUsers(){
/*
* dbConncect Class Connection variable access
*/
$connection = $this->con;
}
}
这是正确的吗?我无法访问dbConnect Class $ con varibale使用$ this->带有sampleView类的方法
并且可以通过这种方式完成不同的位置类扩展,包括页面。帮助Plezzzz
答案 0 :(得分:2)
即使扩展父类,也无法访问private
个变量。您需要将其更改为protected
:
protected $con;
您还需要构造父类,否则它将不会实例化父(扩展)类。
function __construct() {
parent::__construct($host, $username, $password, $db);
}
以上内容将在class SimpleViews extends dbConnect {....
班级
答案 1 :(得分:0)
dbConnect页面
改变
protected $host;
protected $dbName;
protected $uname;
protected $upass;
protected $con;
和SampleView页面
public function __construct() {
parent::__construct('localhostr', 'test', 'root', '');
}
function chkConnection() {
/*
* dbConncect Class Connection variable access
*/
$dbcon = $this->con;
if ($dbcon) {
echo "successfully Connect database";
} else {
echo "sorry Could not be connect databsae";
}
}
有人会更正我的代码吗?