[英]Can I get values for my protected variables from outside a class?
我想從配置文件中獲取變量。
首先,我有一堂課,有這樣的:
var $host;
var $username;
var $password;
var $db;
現在我有這個:
protected $host = 'localhost';
protected $username = 'root';
protected $password = '';
protected $db = 'shadowcms';
這在__construct函數中用於我的mysqli連接
但是現在我需要在類本身中插入值,而不是從配置文件中獲取它們。
受保護的成員不能從類外部直接訪問。
如果需要,您可以提供訪問器來獲取/設置它們。 您也可以將它們聲明為公開並直接訪問。
http://php.net/manual/zh/language.oop5.visibility.php
聲明為protected的成員只能在該類內部以及繼承的和父類訪問。
換句話說,在配置類中,您定義了受保護的屬性。 只能通過繼承該配置類來(直接)訪問它們。
class ConfigBase
{
protected $host = 'localhost';
}
class MyConfig
{
public function getHost()
{
return $this->host;
}
}
$config = new MyConfig();
echo $config->getHost(); // will show `localhost`
echo $config->host; // will throw a Fatal Error
您可以將getter與變量變量一起使用,例如
public function get($property) {
return $this->$property;
}
那你就可以做
$classInstance->get('host');
例如。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.