Type casting for user defined objects

前端 未结 11 1546
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 01:35

Just like we do with __ToString, is there a way to define a method for casting?

$obj = (MyClass) $another_class_obj;
11条回答
  •  独厮守ぢ
    2020-11-29 02:01

    I reworked the function Josh posted (which will error because of the undefined $new_class variable). Here's what I got:

    function changeClass(&$obj, $newClass)
    {   $obj = unserialize(preg_replace // change object into type $new_class
        (   "/^O:[0-9]+:\"[^\"]+\":/i", 
            "O:".strlen($newClass).":\"".$newClass."\":", 
            serialize($obj)
        ));
    }
    
    function classCast_callMethod(&$obj, $newClass, $methodName, $methodArgs=array())
    {   $oldClass = get_class($obj);
        changeClass($obj, $newClass);
    
        // get result of method call
        $result = call_user_func_array(array($obj, $methodName), $methodArgs);
        changeClass(&$obj, $oldClass);  // change back
        return $result;
    }
    

    It works just like you'd expect a class cast to work. You could build something similar for accessing class members - but I don't think I would ever need that, so i'll leave it to someone else.

    Boo to all the jerks that say "php doesn't cast" or "you don't need to cast in php". Bullhockey. Casting is an important part of object oriented life, and I wish I could find a better way to do it than ugly serialization hacks.

    So thank you Josh!

提交回复
热议问题