Метод getBoolean класса InputBag
Метод getBoolean класса InputBag возвращает значение параметра в виде boolean.
Первым параметром передаётся имя параметра.
Вторым параметром можно передать значение по умолчанию,
которое будет возвращено, если параметр отсутствует.
Метод приводит строковые значения '1', 'true', 'on', 'yes' к true,
а все остальные - к false.
Синтаксис
public function getBoolean(string $key, bool $default = false): bool
Пример
Давайте получим boolean-значение из GET-параметра active:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(Request $request): Response
{
$bag = $request->query;
$res = $bag->getBoolean('active');
return new Response(var_export($res, true));
}
}
?>
Результат выполнения кода для адреса /article?active=1:
true
Пример
Давайте передадим значение по умолчанию вторым параметром:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(Request $request): Response
{
$bag = $request->query;
$res = $bag->getBoolean('active', true);
return new Response(var_export($res, true));
}
}
?>
Результат выполнения кода для адреса /article:
true
Пример
Давайте получим boolean-значение из POST-параметра published:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(Request $request): Response
{
$bag = $request->request;
$res = $bag->getBoolean('published');
return new Response(var_export($res, true));
}
}
?>
Результат выполнения кода для POST-запроса с параметром published=true:
true