Skip to content

"Real" method overloading vs Union types #17813

@procodix

Description

@procodix

Description

I think it's time to re-raise a question that has only ever been partially answered and implemented in the past, limited by the current state of development of PHP.

How should PHP methods support overloading?

Historically there were the magic methods like __call(). Now there are Union Types and named parameters to allow different signatures for one method. This was called and sold as method overloading, although it is actually not. Union types in particular feel like an extreme step backwards from strong and clean typing. It is no substitute for method overloading, as it requires unsightly type queries in the code and the order is not flexible, not to mention variadic arguments. In a way, Union Types are the counterpoint to method overload. Named parameters mess with variadic arguments and only work together in some limited use cases.

„Method Overloading“ by the book however should allow multiple methods of the same name with different argument lists. Ideally, even static and instance methods with the same name can coexist. In the days when PHP had no typing, this was not feasible. But fortunately that has changed, so now the way is clear.

Sure, you can simulate all of this with __call(), but that destroys any typing and also the IDE support. I think it's time to merge all the partial concepts into a holistic solution of real method overloading, the same way it is offered in other modern languages. Since this could be added as a new language feature, the current substitutes can still be usable for compatibility reasons, albeit less powerful and therefore lower-value.

Constructors are a primary use case, but other methods up to property hooks also benefit from it.

// representing a HTML Element
class Element {
	function fromHtml(string $html) {...}
	function fromContentClasses(string $content, string $classes) {...}
	function fromContentClassesTag(string $content, string $classes, string $tag) {...}
	function fromDom(DOM $dom, string $selector) {…}

	// vs
	
	function __construct(string $html) {…}
	function __construct(string $content, string $classes) {…}
	function __construct(DOM $dom) {…}
	...

	// property hooks with overloading and automatic type conversion
	array $children {
		get {…}
		set(string $html) {…}
		set(array $elements) {…}
		set(Element $e) {...}
	}
}

Please let me know, if it would make sense to put effort into creating an RFC for this.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions