php overload = operator [duplicate]

巧了我就是萌 提交于 2019-12-18 07:39:32

问题


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


回答1:


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").




回答2:


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';



回答3:


Have a look at the PECL Operator overloading extension.



来源:https://stackoverflow.com/questions/7335765/php-overload-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!