[英]How do I access parent property from subclass? PHP
我在從子級類訪問頂級變量時遇到問題。 這是一個例子...
應用程序.php:
class Application {
var $config;
var $db;
function __construct() {
include_once('Configuration.php');
include_once('Database.php');
$this->config = new Configuration;
$this->db = new Database;
}
}
配置.php:
class Configuration {
var $dbhost = 'localhost';
}
數據庫.php:
class Database {
function __construct() {
echo parent::config->dbhost;
}
}
我很清楚,這里使用parent是錯誤的,因為子類沒有擴展父類,但我如何訪問它?
謝謝你。
您應該創建一個在其構造中創建$db
鏈接的Base
類。 然后讓所有需要數據庫訪問的類擴展該類。 您在此處使用“父類”的命名法不正確。
class Base {
private $db; // Make it read-only
function __construct() {
$this->db = DB::connect(); // It's a good practice making this method static
}
function __get($property) {
return $this->$property;
}
}
class Application {
public $config;
function __construct() {
parent::__construct();
require_once 'Configuration.php';
require_once 'Database.php';
$this->config = new Configuration();
}
function random_function() {
$this->db(....) // Has full access to the $db link
}
}
父符號用於訪問對象層次結構中對象的父對象。 你在這里做的是試圖找到來電者,而不是父母
您這樣做的方法是將您的配置實例傳遞給數據庫對象。
class Database {
protected $config;
public function __construct(Configuration $config){
$this->config = $config;
}
public function connect(){
//use properties like $this->config->username to establish your connection.
}
}
當您擴展類並使子類調用父類上的方法時,將使用父表示法。
class MySuperCoolDatabase extends Database {
protected $is_awesome;
public function __construct(Configuration $config){
// do all the normal database config stuff
parent::__construct($config);
// make it awesome
$this->is_awesome = true;
}
}
這定義了一個子類,它是一個類型定義,其作用與基類相同,但實現略有不同。 這樣的實例仍然可以說是一個數據庫......只是一種不同類型的數據庫。
好吧,雖然我認為 Orangepills 的答案更好。 如果您不想使用它並且由於所有變量都是公開的,您可以簡單地傳遞這樣的變量:
class Application {
var $config;
var $db;
function __construct() {
include_once('Configuration.php');
include_once('Database.php');
$this->config = new Configuration;
$this->db = new Database($this->config->dbhost);
}
}
class Configuration {
var $dbhost = 'localhost';
}
class Database {
function __construct($dbhost) {
echo $dbhost;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.