获取受保护对象中的字符串

4

我正在尝试获取名为$object的对象中受保护的数据字符串"this info",但是如何访问该数据?

    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 给我一个错误:无法访问受保护的属性

1
如果该值受到保护,那么肯定有很好的理由“为什么”。 - tereško
1
嗯,我也遇到了同样的问题,Quickbook API :) - Basheer Kharoti
4个回答

6

有几种替代方法可以获取对象的私有/受保护属性,而不需要修改原始源代码。

选项1 - 反射:

维基百科定义了反射:

......计算机程序在运行时检查和修改程序的结构和行为(具体是值、元数据、属性和函数)的能力。 [反射(计算机编程)]

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

我不建议使用反射,除非您有非常特定的用例需要使用。这是一个使用PHP反射获取私有/受保护参数的示例:

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

选项2 - 子类(仅限受保护属性):

如果该类不是最终类,您可以创建原始类的子类。这将使您可以访问受保护的属性。在子类中,您可以编写自己的getter方法:

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

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

希望这有所帮助。

反射很棒。 - Francis Alvin Tan

4
如果你或者类的作者希望其他人能够访问受保护或私有的属性,那么你需要在类自身中提供一个getter方法。所以在这个类中:
public function getData()
{
  return $this->_data;
}

在您的程序中:
$object->getData();

0

要检索受保护的属性,您可以使用ReflectionProperty接口。

phptoolcase有一个漂亮的方法来完成这个任务:

public static function getProperty( $object , $propertyName )
        {
            if ( !$object ){ return null; }
            if ( is_string( $object ) ) // static property
            {
                if ( !class_exists( $object ) ){ return null; }
                $reflection = new \ReflectionProperty( $object , $propertyName );
                if ( !$reflection ){ return null; }
                $reflection->setAccessible( true );
                return $reflection->getValue( );
            }
            $class = new \ReflectionClass( $object );
            if ( !$class ){ return null; }
            if( !$class->hasProperty( $propertyName ) ) // check if property exists
            {
                trigger_error( 'Property "' . 
                    $propertyName . '" not found in class "' . 
                    get_class( $object ) . '"!' , E_USER_WARNING );
                return null;
            }
            $property = $class->getProperty( $propertyName );
            $property->setAccessible( true );
            return $property->getValue( $object );
        }


$value = PtcHandyMan::getProperty( $your_object , ‘propertyName’);

$value = PtcHandyMan::getProperty( ‘myCLassName’ , ‘propertyName’); // singleton

0
你可以使用著名的getter和setter方法来访问私有/受保护的属性。 例如:
<?php

class myClass
{
    protected $helloMessage;

    public function getHelloMessage()
    {
        return $this->helloMessage;
    }

    public function setHelloMessage( $value )
    {
        //Validations
        $this->helloMessage = $value;
    }
}

?>

您好,

Estefano。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接