Skip to content

Instantly share code, notes, and snippets.

@2no
Created July 17, 2011 07:26
Show Gist options
  • Save 2no/1087306 to your computer and use it in GitHub Desktop.
Save 2no/1087306 to your computer and use it in GitHub Desktop.
PHP5 でオブジェクトを何でもキャスト
<?php
// http://stackoverflow.com/questions/2226103/how-to-cast-objects-in-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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment