2013-04-15 51 views
1

我想從配置文件中獲取我的變量。我可以從課外獲得受保護變量的值嗎?

首先我有一個類,它有這樣的:

var $host; 
var $username; 
var $password; 
var $db; 

現在我有這樣的:

protected $host = 'localhost'; 
protected $username = 'root'; 
protected $password = ''; 
protected $db = 'shadowcms'; 

這是在__construct函數用於我的mysqli連接

但現在我需要在類中插入這些值,而不是從配置文件中獲取它們。

+0

如果你想這樣做,不要保護他們(從一開始就這樣做) – 2013-04-15 21:00:53

回答

4

受保護的成員不能從課外直接訪問。

如果您需要這樣做,您可以提供accessors來獲取/設置它們。你也可以聲明它們並直接訪問它們。

2

http://php.net/manual/en/language.oop5.visibility.php

聲明爲受保護成員只能在類 本身和繼承和父類訪問。

換句話說,在你的配置類中你定義了受保護的屬性。只能通過繼承該配置類來直接訪問它們。

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 
0

您可以使用一個getter具有可變的變量,如

public function get($property) { 
    return $this->$property; 
} 

然後,你可以做

$classInstance->get('host');

例如。

相關問題