Skip to content

add words on why generics don't help. #3

@Danack

Description

@Danack

https://en.reddit.com/r/PHP/comments/rv11fc/operator_overloading_rfc_is_in_voting_what_are/hr316wy/

–]john7 points 2 days ago*
I can't wait for it. The reason is that I use lots of lazy evaluations; old version of example is here.

So I could have a function like this:

function doSomething(int|LazyValue $param): int {
return $param + 42;
}

but without operator overload:

function doSomething(int|LazyValue $param): int {
if ($param instanceof LazyValue) {
$param = $param->getValue();
}

return $param + 42;

}

Updated:

I would prefer for RFC to require interfaces, if possible:

interface Addable
{
public function add(int|float|Addable $param): int|float|Addable
}

End result:

function doSomething(int|Addable $param): int {
return $param + 42;
}

Interfaces would make easier job for static analysis, allow ctrl+click to find all Addable implementations and avoid some WTF situations in older apps with __add() method.

[–]Danack 2 points 2 days ago
I would prefer for RFC to require interfaces, if possible:

Did read the reasons why that isn't appropriate in the RFC ?

https://wiki.php.net/rfc/user_defined_operator_overloads#why_not_interfaces

permalinkembedsaveparenteditdisable inbox repliesdeletereply

[–]john 1 point 1 day ago*
I did, but I think it is mostly because of lack of generics.

For example:

interface Addable
{
public function add(T $param): T
}

class Money implements Addable<int|Money>{}

But I could be wrong, that's why I said if possible; maybe other contributors can come up with some idea.

permalinkembedsaveparentreportgive awardreply

[–]Danack 3 points 1 day ago
That doesn't help anything. If you're using an interface as a type e.g.

function foo (Addable $x, int $y)
{
return $x + $y;
}
You can't tell if the code is valid or not from the interface.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions