LoginSignup
3
2

More than 5 years have passed since last update.

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

Last updated at Posted at 2012-02-11

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

参考: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;
    }
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2