marcioAlmada / yay

Yay is a high level PHP preprocessor
https://github.com/marcioAlmada/yay
MIT License
572 stars 35 forks source link

operator overloading #44

Closed chris-kruining closed 6 years ago

chris-kruining commented 6 years ago

As suggested here I create this to discus ideas.

I would like to see an operator overloading feature, where I might overload for example the + operator.

class Foo
{
    public function __construct(int $value)
    {
        $this->value = $value;
    }

    /** @overload + */
    public function addSome(Foo $foo)
    {
        return $this->value + $foo->value;
    }
}

$foo1 = new Foo(10);
$foo2 = new Foo(5);

var_dump($foo1 + $foo2);

This would then translate to

var_dump($foo1->addSome($foo2));

+= would be its own operator. and maybe a more advanced way would be that the use case of the + would determine which method would be called based on method signature, that is


class Foo
{
    public function __construct(int $value)
    {
        $this->value = $value;
    }

    /** @overload + */
    public function addSomething(int $foo)
    {
        return $this->value + $foo->value;
    }

    /** @overload + */
    public function addSomethingElse(float $foo)
    {
        return $this->value + $foo->value;
    }
}

$foo + 10
$foo + 0.0125

Would become

$foo->addSomething(10);
$foo->addSomethingElse(0.0125);

I would like to emphasize that I'm just throwing out ideas, I have no concrete idea of how the implementation would be done

marcioAlmada commented 6 years ago

I just tried to see how doable it would be on preprocessing time, but this sort of things really needs runtime support.

I'd love to see this RFC moving forward: https://wiki.php.net/rfc/operator-overloading

chris-kruining commented 6 years ago

agreed, although I'm not sure on the 'magic method syntax'. on the other hand if we got getter and setter syntax like es6 then on many an occasion operators like += would be handler quite nicely IMHO