Re: Concept: constructor overloading syntax sugar
| From: | Tim Düsterhus | Date: | Tue, 18 Feb 2025 11:36:00 +0000 |
| Subject: | Re: Concept: constructor overloading syntax sugar | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-126442@lists.php.net to get a copy of this message | ||
Hi
Am 2025-02-18 09:00, schrieb Rowan Tommins [IMSoP]:
Personally, I think quite the opposite: named constructors make a lot more sense than type-based overloads. For instance, you might have both createFromJson and createFromYaml; their inputs are both going to be "string" as far as the type system is concerned, so overloading would be useless.To add an example from PHP’s standard library: The new DOM API shipped in PHP 8.4 uses named constructors to create documents and requires this to distinguish between
createFromFile and createFromString.
https://github.com/php/php-src/blob/da38477544c76c2f034ad74dfd2e1fe613030a31/ext/dom/php_dom.stub.php#L2041-L2045
final class HTMLDocument extends Document
{
public static function createEmpty(string $encoding = "UTF-8"): HTMLDocument {}
public static function createFromFile(string $path, int $options = 0, ?string $overrideEncoding = null): HTMLDocument {}
public static function createFromString(string $source, int $options = 0, ?string $overrideEncoding = null): HTMLDocument {}
// […]
}
Best regards
Tim Düsterhus