我正在尝试获取此对象中的字符串“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/