2013-04-24 44 views
3

我正在創建一個新的ReflectionClass,然後將受保護的屬性_products設置爲可訪問。它總是返回null我在這裏做錯了什麼?我在5.4.11爲什麼getProperty通過PHP ReflectionClass返回null

$project = new ReflectionClass($instance_of_object); 
$property = $project->getProperty('_products'); 
$property->setAccessible(true); 
$products = $property->getValue($project); 

我想,以確保財產在我的單元測試正確設置...

+0

編輯有答案以上:) 5.4.11 – 2013-04-24 23:03:29

+0

你** **肯定的屬性不是'null' ? – hek2mgl 2013-04-24 23:04:19

+0

你有涉及的任何命名空間嗎? – bestprogrammerintheworld 2013-04-24 23:06:33

回答

2

我準備工作簡單的例子。如果你可以執行它,必須有其他地方的錯誤代碼:

class The_Class { 

    private $_products; 

    public function __construct() { 
     $this->_products = 'foo'; 
    } 
} 

$instance_of_class = new The_Class(); 
$reflClass = new ReflectionClass($instance_of_class); 
$member = $reflClass->getProperty('_products'); 
$member->setAccessible(true); 
// Here is an error in your code: 
// Note that I'm using $instance_of_class, rather then 
// $reflClass as argument to getValue() 
var_dump($member->getValue($instance_of_class)); // string(3) "foo" 
+0

有趣......你在什麼版本?跟我一樣?我們還默認'_products'爲'false'(我可能會改變它),但在課程中設置它後,它仍然對我說'null'。我想我會三重檢查。如果你沒有在構造函數中設置,並且在聲明中將其默認設置爲3,那麼這對你有用嗎? – 2013-04-24 23:34:03

+0

我不確定我是否正確理解你,但[pastebin](http://pastebin.com/UbGZWmuy)適合我。我正在使用PHP5.3.10 – hek2mgl 2013-04-24 23:37:02

+0

如果你刪除了構造函數,它還能工作嗎?傻我說,把它設置爲「3」我的意思是說「富」,看它是否會起作用,如果它從開始 – 2013-04-24 23:39:00