【问题标题】:Property of type X may not have default valueX 类型的属性可能没有默认值
【发布时间】:2022-09-27 19:20:04
【问题描述】:

我想在 php 中定义类型化类,遵循最近的类型特性(用作https://github.com/rutek/dataclass 的一部分)。下面返回错误“CustomType 类型的属性可能没有默认值” - 如何定义 CustomType 以便允许使用默认值?值得注意的是,无论在此处放置什么默认值,都会发生这种情况。

class CustomType {
    public string $item;
}

class NewClass {
    public CustomType $test = transform(\'CustomType\', array(\'item\' => \'testitem\'));;
}

编辑:根据答案,我修改了我的问题,使默认值为 CustomType 类型。我没有指定的是我想通过修改 CustomType 而不是 NewClass 来实现这一点。这应该是可能的,因为像 int 这样的默认类型具有这种行为:

class NewClass {
    public int $test = 1;;
}

    标签: php


    【解决方案1】:

    首先,在这个作业中:

    public CustomType $test = array("item"=>"testitem");
    

    左边是CustomType 类型,所以它需要CustomType 的一些实例,但右边是array

    然后,它实际上可能没有默认值。要通过 Dataclass 库调整它,您应该使用如下构造函数:

    require_once 'vendor/autoload.php'; // Make sure the path here is correct
    
    use function Rutek\Dataclass\transform;
    
    class CustomType {
        public string $item;
    }
    
    class NewClass {
    
        public CustomType $test;
    
        public function __construct()
        {
            $this->test = transform('CustomType', array('item' => 'testitem'));
        }
    }
    
    // Check the result
    $c = new NewClass;
    var_dump($c);
    

    【讨论】:

    • 谢谢您-我已根据您的回答将问题修改为更具体
    猜你喜欢
    • 2019-08-06
    • 2011-04-28
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    相关资源
    最近更新 更多