I would like to know if I can use Partial
like typescript.
For instance I have this class:
class Registration {
public function __construct(
public readonly int $year,
public readonly int $coverage,
public readonly string $start_date,
public readonly string $state_address,
) {
}
}
Is there a way to create a class from the original, with those rules:
- Don’t modify the original class.
- Don’t create a constructor in the child class.
- Make all properties partial.
It there like a magic function in PHP that can do it? Something like this:
class RegitrationPartial extends Partial(Registration) { }
Now I can call that class in this way:
new RegitrationPartial(year: 2025);
0
You can use something called named arguments, this allows you to specify the exact argument you want to populate. Your actually pretty close already.
<?php
class Registration {
public function __construct(
public readonly ?int $year = null,
public readonly ?int $coverage = null,
public readonly ?string $start_date = null,
public readonly ?string $state_address = null,
) {
//
}
}
$Registration = new Registration(year: 2025);
Some further reading on named arguments
https://stitcher.io/blog/php-8-named-arguments
4
You can create a RegistrationPartial class that extends the original class and uses optional parameters in its constructor, providing null as default values. after that, you can send those optional parameters to the parent class based on whether they are provided or not.
this one should work:
class Registration {
public function __construct(
public readonly int $year,
public readonly int $coverage,
public readonly string $start_date,
public readonly string $state_address
) { }
}
class RegistrationPartial extends Registration {
public function __construct(
?int $year = null,
?int $coverage = null,
?string $start_date = null,
?string $state_address = null
) {
parent::__construct(
$year ?? 0, // Provide default or placeholder value
$coverage ?? 0,
$start_date ?? '',
$state_address ?? ''
);
}
}
// Usage:
$partial = new RegistrationPartial(year: 2025);
1