2012-03-29 40 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