2012-03-29 43 views
4

我想让这个对象中的字符串“this info”让我们调用它$object,但是数据是受保护的,我怎样才能访问这个口袋?获取受保护对象中的字符串

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给我一个错误Cannot access protected property

+1

如果该值是受保护的,那么有一个很充分的理由“为什么”。 – 2012-03-29 18:40:23

+1

以及我已经面临同样的问题QuickBook api :) – 2015-10-19 11:17:10

回答

4

如果你 - 或者类的作家 - 希望其他人能够访问受保护的或私有财产,你需要提供通过getter方法在课堂上。

所以在类:

public function getData() 
{ 
    return $this->_data; 
} 

而在你的程序:

$object->getData(); 
0

您可以使用著名的getter和setter方法,私有/保护性能。 例如:

<?php 

class myClass 
{ 
    protected $helloMessage; 

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

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

?> 

问候,

埃斯特凡诺。

5

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

选项1 - Reflection

维基百科定义为反射

...中的计算机程序的检查和修改的结构和行为(具体地,值,元数据的能力,属性和功能)在运行时。 [Reflection (computer_programming)]

在这种情况下,你可能想使用反射来检查对象的属性,并设置为访问保护财产_data

我不建议反射,除非你有非常具体的使用情况下,它可能是必需的。这是一个关于如何使用Reflection用PHP来获得您的私人/保护参数的例子:

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

选项2 - 子类(只保护性能):

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

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

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

希望这会有所帮助。

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