John Davidson

php - Property of type X may not have default value

0 comments
Message:


I want to define typed classes in php, following the recent type features (to be used as part of https://github.com/rutek/dataclass). The below returns the error "Property of type CustomType may not have default value" - how do I define CustomType such that it is allowed a default value? Notably this occurs no matter what default value is placed here.


class CustomType {
public static string $item;
public function __construct(string $item) {
$this->item = $item;
}
}

class NewClass {
public CustomType $test = CustomType("1");
}

Edit: Based on answers I have modified my question such that the default value is of type CustomType. What I didn't specify is I would like to achieve this by modifying CustomType rather than NewClass. This should be possible, as default types like int have this behaviour:


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

Edit 2: I discovered the Dataclass library uses a built-in function to obtain the default values: https://www.php.net/manual/en/reflectionclass.getdefaultproperties.php
This is at least one piece of the puzzle! It's the validation of these defaults that I wish to edit.


Edit 3: The lack of static classes in php means I think what I'm trying to do may not be possible in this way - I've edited the original question to the "ideal world" syntax



My Answer:
"Property of type X may not have default value" because in PHP, when defining typed properties in a class, you cannot provide a default value for them. Typed properties were introduced in PHP 7.4 and they must be initialized explicitly in the constructor.

Here is an example of how you can define typed properties in a class without default values:

php
class MyClass {
public int $number;

public function __construct(int $number) {
$this->number = $number;
}
}

$obj = new MyClass(10);
echo $obj->number; // Output: 10


In this example, the `number` property is defined as an integer type and it is initialized in the constructor. This way, you can ensure that the property has a valid value of the specified type when an object of the class is created.

Rate this post

5 of 5 based on 1855 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us