我正在使用 PHP 7.4 和属性类型提示。
假设我有一个 A 类,有几个私有属性。当我使用 \SoapClient、Doctrine ORM 或任何绕过构造函数并使用反射直接获取/设置属性来实例化类的工具时,我会遇到错误PHP Fatal error: Uncaught Error: Typed property A::$id must not be accessed before initialization in。
<?php
declare(strict_types=1);
class A
{
private int $id;
private string $name;
public function __construct(int $id, string $name)
{
$this->id = $id;
$this->name = $name;
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
}
$a = (new \ReflectionClass(A::class))->newInstanceWithoutConstructor();
var_dump($a->getId()); // Fatal error: Uncaught Error: Typed property …Run Code Online (Sandbox Code Playgroud) 我在我的 symfony 应用程序中将 Data-Dog/Auditbundle用于 AuditLogs。此外,我还使用 TokenAuthenticator 作为 api 的守卫。但是 bundle 的 EventSubscriber 在 TokenAuthenticator 之前被调用,因此
public function __construct(TokenStorageInterface $securityTokenStorage)
{
$this->securityTokenStorage = $securityTokenStorage;
}
Run Code Online (Sandbox Code Playgroud)
EventSubscriber 中的 this 将令牌设为 null,我无法获取用户。
我试图将我的 BaseService 注入到另一个服务中,我需要调用我在 BaseService 中编写的存储库。
我认为这很简单,但它用以下标记 __construct 部分:
缺少父构造函数调用
我在 BaseService 中创建了该逻辑并且它有效
class BaseService
{
/** @var ContainerInterface */
public $container;
public $em;
public function __construct(ContainerInterface $container, EntityManagerInterface $em)
{
$this->container = $container;
$this->em = $em;
}
/**
* @return \Doctrine\Common\Persistence\ObjectRepository|\Doctrine\ORM\EntityRepository
*/
public function getMyDataRepository()
{
return $this->em->getRepository(MyData::class);
}
}
Run Code Online (Sandbox Code Playgroud)
和我的其他服务:
class DataService extends AbstractAdmin
{
public function __construct(BaseService $baseService)
{
$this->baseService = $baseService;
}
public function getTransactions(Card $card)
{
return $this->getMyDataRepository()
->createQueryBuilder('c')
->getQuery();
}
}
Run Code Online (Sandbox Code Playgroud) 我编写了将生日日期转换为年龄的那些代码行。
我将在许多控制器和许多路由功能中使用此代码!所以我决定把它放在一个函数中,然后调用calculate_age().
我的问题是我怎么可以声明函数或任何功能 一旦里面的namespace App\Controller;?所以我可以在所有控制器中使用它。
功能代码:
public function calculate_age($birthday): ?int
{
$current_date = date('d-m-Y', time());
$info = explode(' ', $birthday);
$months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
$numbers = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
$i = 0;
for ($i = 0; $i <= 11; ++$i) {
if ($info[2] == $months[$i]) {
$info[2] = $numbers[$i];
}
}
$all = $info[1].'-'.$info[2].'-'.$info[3];
$difference = …Run Code Online (Sandbox Code Playgroud) php ×4
symfony ×3
declaration ×1
doctrine-orm ×1
function ×1
namespaces ×1
oop ×1
php-7.4 ×1
soap-client ×1
symfony-3.4 ×1