Type casting for user defined objects

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

    You can create two reflection object then copy values to other example can be found at https://github.com/tarikflz/phpCast

        public static function cast($sourceObject)
    {
        $destinationObject = new self();
        try {
            $reflectedSource = new ReflectionObject($sourceObject);
            $reflectedDestination = new ReflectionObject($destinationObject);
            $sourceProperties = $reflectedSource->getProperties();
            foreach ($sourceProperties as $sourceProperty) {
                $sourceProperty->setAccessible(true);
                $name = $sourceProperty->getName();
                $value = $sourceProperty->getValue($sourceObject);
                if ($reflectedDestination->hasProperty($name)) {
                    $propDest = $reflectedDestination->getProperty($name);
                    $propDest->setAccessible(true);
                    $propDest->setValue($destinationObject, $value);
                } else {
                    $destinationObject->$name = $value;
                }
            }
        } catch (ReflectionException $exception) {
            return $sourceObject;
        }
        return $destinationObject;
    }
    

提交回复
热议问题