2013-04-15 50 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');

例如。

相关问题