2016-09-22 45 views
-2

我有一個方法,將參考引用變量設置爲一個新初始化類

// CarService.php 
public function getCars(&$carCollection = null) 
{ 
    $promise = // guzzle request for getting all cars would be here 
    $promise->then(function (ResponseInterface $response) use (&$carCollection) { 
     $cars= json_decode($response->getBody(), true); 
     $carCollection= new CarCollection($cars); 
    }); 
} 

然而,訪問該集合,並試圖重新使用它的時候,我遇到了錯誤

Argument 1 passed to {placeholder} must be an instance of {placeholder}, null given

我知道,這樣做的原因是,該構造函數返回什麼,但我怎麼能還我的變量分配到CarCollection的新實例(延伸學說的ArrayCollection

我甚至有一個靜態方法作爲工作試了一下週圍

// CarCollection.php 
public static function create(array $cars): CarCollection 
{ 
    $carCollection = new CarCollection($cars); 
    return $carCollection; 
} 

// CarService.php 
public function getCars(&$carCollection = null) 
{ 
    $cars = // curl request for getting all cars would be here 
    $carCollection = CarCollection::create($cars) 
} 

,但它仍然是零。這是爲什麼?我如何設置一個引用的變量到一個新的類?

餘像這樣訪問

$carService = $this->get('tzfrs.vehicle.services.car'); 
$carCollection = null; 
$promises = [ 
    $carService->getCars($carCollection) 
]; 

\GuzzleHttp\Promise\unwrap($promises); 

var_dump($carCollection); // null 

當我設置直接參考,例如該方法。

// CarService.php 
public function getCars(&$carCollection = null) 
{ 
    $carCollection = new CarCollection([]); 
} 

它的工作原理沒有任何問題。似乎回調在某種程度上是問題。

無論誰低估了這個,你能否詳細說明爲什麼和爲什麼你投票結束?

+0

你能告訴我們你是如何調用getCars方法嗎? – Petah

+0

當然,我已經添加了一些代碼 – Musterknabe

+0

對不起@PeeHaa,我刪除了它。以爲它會在PHP 7下開發,而不是PHP 7 – Musterknabe

回答

0

我可能會誤解這個問題,但您應該可以在通過引用傳遞時修改對象。在這裏看到的例子:https://3v4l.org/KtFvZ

在您添加後來的示例代碼,你不應該通過引用傳遞$carCollection,該&只應在方法/函數確定指標,當你調用它沒有提供。我不認爲這是你的問題,但應該是在php7中拋出一個錯誤。

+0

你是對的,抱歉。我在方法調用中沒有'&'。是一個寫錯誤。但它仍然不起作用。當我做一個'echo get_class'時,它返回'Controller',在那裏我調用'CarService',所以它看起來像是以某種方式設置自己 – Musterknabe

+0

好吧,我以某種方式跟蹤錯誤。當我直接在方法中設置變量時,它的工作沒有問題,但在我的情況下,我有另一個回調函數,當我在那裏設置'$ carCollection'時,它不起作用。我會更新我的代碼 – Musterknabe