我对空合并运算符(??)有一些疑问。绘制一个小树枝视图。因此,如果用户未被记录,我想将表单设置为null。我给您我的PHP控制器方法代码:
#[Route('/{id}', name: 'app_recipe_show', methods: ['GET', 'POST'], requirements: ['id' => '[1-9]\d*'])]
public function show(Recipe $recipe, UserRepository $userRepository, Request $request): Response
{
$user = $this->getUser();
// If the user is logged
if ($user) {
// If the user is the cooker of the recipe
$isCooker = $user->getId() === $recipe->getCooker()->getId();
// If the recipe is in the user's favorites
$isFavorite = $user->getFavorites() !== null && in_array($recipe->getId(), $user->getFavorites(), true);
// create form to add/remove the recipe to the user's favorites
$favoriteForm = $this->createFormBuilder()
->add('submit', SubmitType::class, ['label' => ($isFavorite) ? 'Remove from favorites' : 'Add to favorites'])
->setMethod('POST')
->getForm();
$favoriteForm->handleRequest($request);
if ($favoriteForm->isSubmitted() && $favoriteForm->isValid()) {
if ($isFavorite) {
// remove the recipe from the user's favorites
$user->removeRecipeFromFavorites($recipe->getId());
} else {
// add the recipe to the user's favorites
$user->addRecipeToFavorites($recipe->getId());
}
// persist the user and flush it
$userRepository->add($user, true);
// redirect to the recipe show page
return $this->redirectToRoute(
'app_recipe_show',
['id' => $recipe->getId()],
Response::HTTP_SEE_OTHER
);
}
}
return $this->render('recipe/show.html.twig', [
'recipe' => $recipe,
'is_cooker' => $isCooker ?? false,
'is_favorite' => $isFavorite ?? false,
// null coalescing operator (??) set the form to null if the user is not logged
'favorite_form' => $favoriteForm->createView() ?? null,
]);
}
我有一个错误告诉变量$favoriteForm是未定义的。什么是正常的!我该怎么做?
发布于 2022-10-01 12:12:56
是的,这种行为是正常的。这是因为??
正在计算createView()
的结果,但是不能执行它,因为没有定义$favoriteForm
:只有在有用户登录的情况下才有条件创建$favoriteForm
。
如果您使用的是php >= 8.0,则需要使用无空算子:
'favorite_form' => $favoriteForm?->createView(),
如果您的版本较低,则必须使用更简洁的结构:
'favorite_form' => isset($favoriteForm) ? $favoriteForm->createView() : null,
而且,由于它的使用,它没有什么意义,因为根据文献资料
空合并操作符(??) ..。如果存在且不是null,则返回其第一个操作数;否则返回其第二个操作数。
如果createView()
返回null
,那么合并到null
将是不可行的。
https://stackoverflow.com/questions/73917881
复制相似问题