将引用变量设置为新初始化的类


Set a referenced variable to a newly initialized class

我有一个方法,它接受一个引用

// 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的新实例(它扩展了Doctrine的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([]);
}

它工作没有任何问题。似乎是回调出了问题。

谁否决了这个,你能详细说明为什么和为什么你投票关闭吗?

我可能误解了这个问题,但是您应该能够在通过引用传递时修改对象。这里有一个例子:https://3v4l.org/KtFvZ

在您添加的后面的示例代码中,您不应该通过引用传递$carCollection, &应该只在方法/函数定义中,而不是在调用它时提供。我不认为这是你的问题,虽然,这应该抛出一个错误在php7。