php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #49691 __operator() magic method
Submitted: 2009-09-27 21:05 UTC Modified: 2010-12-22 15:37 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: generalpd at gmx dot de Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: * OS: *
Private report: No CVE-ID: None
 [2009-09-27 21:05 UTC] generalpd at gmx dot de
Description:
------------
My suggestion is a new magic method called __operator($op, $rightValue) or (if that might be the better way) __operator($leftValue, $op)

If defined, a class should be able to handle an operation, like "$classA + $classOrValueB". What the method returns is the result of that of that operation.

Reproduce code:
---------------
// first way
class A1
{
    // the method of the instance of $a1
    public function __operator($operator, $rightValue)
    {
        var_dump($rightValue);    // 'Hi, All!'
        var_dump($operator);      // '.'

        return '666 . ' . $rightValue;
    }
}

// second way
class A2
{
    // the method of the instance of $a2
    public function __operator($leftValue, $operator)
    {
        var_dump($leftValue);    // 'Hello, World!'
        var_dump($operator);     // '+'

        return '777 + ' . $leftValue;
    }
}

// 1st way
$a1 = new A1();
$c1 = $a1 . 'Hi, All!';         // '666 . Hi, All!'
                                // the result of __operator() method

// 2nd way
$a2 = new A2();
$c2 = 'Hello, World!' + $a2;    // '777 + Hello, World!'
                                // the result of __operator() method


Expected result:
----------------
$c1 = '666 . Hi, All!';
$c2 = '777 + Hello, World!';

Actual result:
--------------
-----

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-03-09 21:42 UTC] ziddiri at yahoo dot com
It is one of most important oo thing that is missing in php. And I share same thought with you. It should be included in 5.3.x or in php 6.
 [2010-12-20 15:43 UTC] jani@php.net
-Package: Feature/Change Request +Package: Class/Object related
 [2010-12-20 15:43 UTC] jani@php.net
-Operating System: all +Operating System: * -PHP Version: 5.3.0 +PHP Version: *
 [2010-12-22 15:37 UTC] johannes@php.net
-Status: Open +Status: Bogus
 [2010-12-22 15:37 UTC] johannes@php.net
pecl.php.net/operator exists. but in a weakly typed scripting language operator overloading easily leads to unmaintainable code.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 17:01:58 2024 UTC