小编Jul*_* B.的帖子

PHP 7.4+ 类属性类型

我确信这个问题已经被问过很多次了,但我似乎找不到一个好的/令人满意的答案,所以请直接告诉我。

使用 PHP 7.4+,我倾向于输入我能输入的所有内容。但我对学说实体属性有一些问题。

如果我正确输入所有内容,我通常会遇到很多像这样的错误。

初始化之前不得访问类型化属性 App\Entity\User::$createdAt

该类型错误的代码示例如下所示

/**
 * @var DateTimeInterface
 * @ORM\Column(type="datetime")
 */
protected DateTimeInterface $createdAt;
Run Code Online (Sandbox Code Playgroud)

因此,我曾经使属性可以为空,即使数据库字段不是。所以它看起来像这样。

/**
 * @var DateTimeInterface|null
 * @ORM\Column(type="datetime")
 */
protected ?DateTimeInterface $createdAt = null;
Run Code Online (Sandbox Code Playgroud)

但是,现在我有另一个问题。我决定在我的项目中实现静态代码分析器,现在我使用 PHPStan。所以现在,当我扫描代码时,我会收到类似的错误。


src/Entity/Trait/TimestampableEntityPropertiesTrait.php 行(在 App\Entity\Article 类的上下文中)


16 属性 App\Entity\Article::$createdAt 类型映射不匹配:属性可以包含 DateTimeInterface|null 但数据库需要 DateTimeInterface。


那么,处理这种情况的正确方法是什么?

任何建议将不胜感激。

编辑

我应该提到,有时,我不想/无法初始化构造函数中的属性,因为我还没有正确的值。

php phpstan

5
推荐指数
1
解决办法
1833
查看次数

在 PHP 中通过 PhpStan 使用 Enum 作为字符串

我正在 Symfony 6 应用程序中试验 PHP 枚举,我认为我找到了一个非常好的用例。一切正常,但 phpstan 一直抱怨我返回的类型。

 ------ -----------------------------------------------------------------------------------------------------------------------------------------------
  Line   src/Entity/User.php
 ------ -----------------------------------------------------------------------------------------------------------------------------------------------
  93     Return type (array<App\Security\Roles>) of method App\Entity\User::getRoles() should be compatible with return type (array<string>) of method
         Symfony\Component\Security\Core\User\UserInterface::getRoles()
 ------ -----------------------------------------------------------------------------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

我的枚举看起来像这样:

namespace App\Security;

enum Roles: string
{
    case Admin = 'ROLE_ADMIN';
    case User = 'ROLE_USER';
}
Run Code Online (Sandbox Code Playgroud)

在我User实现的实体中Symfony\Component\Security\Core\User\UserInterface,我有这个:

/**
 * @see UserInterface
 * @return array<Roles>
 */
public function getRoles(): array
{
    $roles = $this->roles;
    // guarantee every user at least has ROLE_USER
    $roles[] = …
Run Code Online (Sandbox Code Playgroud)

php enums static-analysis symfony phpstan

5
推荐指数
1
解决办法
2840
查看次数

来自不同模块的类继承python

我是 python 的新手,我很难弄清楚如何从其他模块中的类继承。

模块:~/foo.py

import bar

class foo:
    def test(self)
        print("this is a test")
Run Code Online (Sandbox Code Playgroud)

模块:~/bar.py

class bar(foo):
    def __init__(self):
        super().test()
Run Code Online (Sandbox Code Playgroud)

导入 bar 后,我收到此错误消息:

NameError: name 'foo' is not defined
Run Code Online (Sandbox Code Playgroud)

inheritance module class python-3.x

2
推荐指数
1
解决办法
2253
查看次数