Created
July 17, 2011 07:26
-
-
Save 2no/1087306 to your computer and use it in GitHub Desktop.
PHP5 でオブジェクトを何でもキャスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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