2009-12-22 72 views
17

我有以下PHP5代碼:如何修復PHP嚴格錯誤「從空值創建默認對象」?

$request = NULL; 
$request->{"header"}->{"sessionid"}  = $_SESSION['testSession']; 
$request->{"header"}->{"type"}    = "request"; 

第2和第3生產以下錯誤:

PHP Strict standards: Creating default object from empty value

我怎樣才能解決這個問題?

+1

只是好奇,你以前在哪裏看到這樣的風格? $ request - > {「header」} - > {「sessionid」} – MindStalker 2009-12-22 23:58:30

+0

我在看到JSON請求時看到了它。 – Jake 2009-12-23 00:04:11

回答

40

空不是一個對象,所以你不能給它賦值。從你在做什麼看起來你需要一個associative array。如果您在使用對象死心塌地,你可以使用stdClass

//using arrays 
$request = array(); 
$request["header"]["sessionid"]  = $_SESSION['testSession']; 
$request["header"]["type"]    = "request"; 

//using stdClass 
$request = new stdClass(); 
$request->header = new stdClass(); 
$request->header->sessionid  = $_SESSION['testSession']; 
$request->header->type    = "request"; 

我會建議使用陣列,它與(可能)相同的底層實現一個整潔的語法。

+0

我無法讓它與stdClass()一起工作..但是,array()風格工作得很好... 謝謝 – Jake 2009-12-23 00:15:38

1

不要嘗試設置空值的屬性?改爲使用關聯數組。

13

擺脫$請求= NULL,代之以:

$request = new stdClass; 
$request->header = new stdClass; 

您正在嘗試寫爲NULL,而不是實際的對象。

4

取消錯誤:

error_reporting(0); 

要修正此錯誤:

$request = new stdClass(); 

心連心

相關問題