Closed akbarali1 closed 6 months ago
Yes, because php itself prohibits assigning readonly values to properties outside the constructor. That's why it's called readonly.
Yes, because php itself prohibits assigning readonly values to properties outside the constructor. That's why it's called readonly.
You are wrong, it is possible. I did it myself in DTO.
https://github.com/akbarali1/data-object?tab=readme-ov-file#20-version-supported-readonly-properties
It can be done
class Some
{
public function __construct(
public readonly string $foo
) {
}
}
die((new Some('foo'))->foo);
class Some
{
public readonly string $foo;
public function __construct(
string $foo
) {
$this->foo = $foo;
}
}
die((new Some('foo'))->foo);
class Some
{
public readonly string $foo;
public function __construct(
string $foo
) {
$key = 'foo';
$this->$key = $foo;
}
}
die((new Some('foo'))->foo);
abstract class BaseClass
{
public function __construct(
string $foo
) {
$this->foo = $foo;
}
}
class Some extends BaseClass
{
public readonly string $foo;
}
die((new Some('foo'))->foo);
To make this work, we need to move the mechanics of processing incoming data into the __construct
method of the final class. But in this case the question arises - why a DTO package when it will be in the application anyway?
But you can propose your own version of the code without breaking the project structure.
Error: Cannot initialize readonly property App\DTO\YourInstance::$foo from scope DragonCode\SimpleDataTransferObject\DataTransferObject