Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php overload = operator [duplicate]

Possible Duplicate:
Operator Overloading in PHP

Is there a way to overload the = operator ?

So want I is the following:

class b{
    function overloadis(){
       // do somethng
    }
}

$a = new b();
$a = 'c';

In the example above, I want that when $a = 'c'; is called, the method overloadis is called first and then that function desides if the action (assign 'c' to $a) is executed or aborted.

Is it possible to do this ?

Thnx in advance, Bob

like image 715
Bob Avatar asked Sep 07 '11 14:09

Bob


People also ask

Does PHP support operator overloading?

In PHP function overloading is done with the help of magic function __call(). This function takes function name and arguments. Example: php.

What is Operator Overloading in PHP?

When different operations are performed using the same operator, then it is called operator overloading. Similarly, if we define functions having an identical name but different set of arguments, then it is called function overloading. In PHP we have to overload.

How can we overload a method in PHP?

To achieve method overloading in PHP, we have to utilize PHP's magic methods __call() to achieve method overloading. __call(): In PHP, If a class executes __call(), and if an object of that class is called with a method that doesn't exist then, __call() is called instead of that method.

What is function overloading and overriding in PHP?

Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.


3 Answers

No. PHP doesn't support operator overloading, with a few exceptions (as noted by @NikiC: "PHP supports overloading of some operators, like [], -> and (string) and also allows overloading some language constructs like foreach").

like image 157
Piskvor left the building Avatar answered Oct 16 '22 12:10

Piskvor left the building


You can imitate such a feature for class-properties, by using the PHP-magic-function __set() and setting the respective property to private/protected.

class MyClass
{
    private $a;

    public function __set($classProperty, $value)
    {
        if($classProperty == 'a')
        {
            // your overloadis()-logic here, e.g.
            // if($value instanceof SomeOtherClass)
            //     $this->$classProperty = $value;
        }
    }
}

$myClassInstance = new MyClass();
$myClassInstance->a = new SomeOtherClass();
$myClassInstance->a = 'c';
like image 34
feeela Avatar answered Oct 16 '22 13:10

feeela


Have a look at the PECL Operator overloading extension.

like image 3
Orbling Avatar answered Oct 16 '22 11:10

Orbling