PHP

PHP5 でオブジェクトを何でもキャスト

More than 5 years have passed since last update.

あまりオススメできない。

参考:http://stackoverflow.com/questions/2226103/how-to-cast-objects-in-php

php_cast.php
<?php

$a = new A();
$b = cast($a, 'B');
$a->foo(); // A!
$b->foo(); // B!

function cast($obj, $toClass)
{
    if (!class_exists($toClass)) {
        return false;
    }
    $length = strlen($toClass);
    $objIn  = serialize($obj);
    $objOut = '';
    if (preg_match('/\AO:\d+:\".*?\":(.*?)\z/', $objIn, $matches)) {
        $objOut = sprintf('O:%d:"%s":%s', $length, $toClass, $matches[1]);
    }
    return unserialize($objOut);
}

class A
{
    public function foo()
    {
        print 'A!' . PHP_EOL;
    }
}

class B
{
    public function foo()
    {
        print 'B!' . PHP_EOL;
    }
}