php - 获取 protected 对象中的字符串

标签 php object

我正在尝试获取此对象中的字符串“this info”,我们称它为 $object,但数据是 protected ,我如何访问该数据包?

    object(something)#29 (1) {
  ["_data":protected]=>
  array(10) {
    ["Id"]=>
    array(1) {
      [0]=>
      string(8) "this info"
    }
    ["SyncToken"]=>
    array(1) {
      [0]=>
      string(1) "0"
    }
    ["MetaData"]=>
    array(1) {

显然 $object->_data 给我一个错误无法访问 protected 属性

最佳答案

有几种替代方法可以获取对象的私有(private)/ protected 属性,而无需您修改原始源代码。

选项 1 - Reflection :

维基百科将反射定义为

... the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of the program at runtime. [Reflection (computer_programming)]

在这种情况下,您可能希望使用反射来检查对象的属性并将 protected 属性设置为可访问 _data

我不建议使用反射,除非您有可能需要反射的非常具体的用例。这是一个关于如何使用 PHP 反射获取私有(private)/ protected 参数的示例:

$reflector = new \ReflectionClass($object);
$classProperty = $reflector->getProperty('_data');
$classProperty->setAccessible(true);
$data = $classProperty->getValue($object);

选项 2 - 子类(仅限 protected 属性):

如果类不是final ,您可以创建原始的子类。这将使您能够访问 protected 属性。在子类中,您可以编写自己的 getter 方法:

class BaseClass
{
    protected $_data;
    // ...
}

class Subclass extends BaseClass
{
    public function getData()
    {
        return $this->_data
    }
}

希望这对您有所帮助。

关于php - 获取 protected 对象中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9930843/

相关文章:

php - 在没有匹配行的情况下,MySQLi 查询返回值

Javascript 使用 JSON 将对象推送到 cookie

javascript - jQuery 1.7.2 AJAX 调用抛出 NS_ERROR_XPC_NOT_ENOUGH_ARGS 错误

php - 在 Windows PHP 5.3.5 中使用 php_fileinfo.dll 和 finfo_open

php - 从一个表中选择 Laravel 5.1 中另一个表中不存在的所有记录

c# - 将根 XML 元素反序列化为数组

python - 为什么相同的 "inputs"会得到两个不同的结果

c++ - 类函数可以有不同类对象的参数吗?

php - 如何让当前用户进入我的实体类?

php - Laravel 从软删除中获取关系