Type casting for user defined objects

前端 未结 11 1582
没有蜡笔的小新
没有蜡笔的小新 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 01:47

    Here's a function to change the class of an object:

    /**
     * Change the class of an object
     *
     * @param object $obj
     * @param string $class_type
     * @author toma at smartsemantics dot com
     * @see http://www.php.net/manual/en/language.types.type-juggling.php#50791
     */
    function changeClass(&$obj,$new_class)
    {
        if(class_exists($class_type,true))
        {
            $obj = unserialize(preg_replace("/^O:[0-9]+:\"[^\"]+\":/i",
                "O:".strlen($class_type).":\"".$new_class."\":", serialize($obj)));
        }
    }
    

    In case it's not clear, this is not my function, it was taken from a post by "toma at smartsemantics dot com" on http://www.php.net/manual/en/language.types.type-juggling.php#50791

提交回复
热议问题