我可以从类外部获取受保护变量的值吗?


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';

在我的mysqli连接的__construct函数中使用

但是现在我需要在类本身中插入值,而不是从配置文件中获取它们。

受保护的成员不能从类外部直接访问。

如果您需要这样做,您可以提供访问器来获取/设置它们。您也可以将它们声明为public并直接访问。

http://php.net/manual/en/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');

例如