Class casting in PHP (very dirty, not for production)
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 | |
/** | |
* Parent class | |
*/ | |
class mother | |
{ | |
protected $myvar; | |
function __construct($value) | |
{ | |
$this->myvar = $value; | |
} | |
} | |
/** | |
* Child class | |
*/ | |
class grandmother extends mother | |
{ | |
protected $bval; | |
function __construct($value) | |
{ | |
$this->bval = $value; | |
$this->myvar = $value / 10; | |
} | |
function __wakeup() | |
{ | |
if (!isset($this->myvar)) throw new Exception("Illegal unserialize: The original object did not contain a myvar property."); | |
$this->bval = $this->myvar * 10; | |
} | |
function getVal() { | |
return $this->bval; | |
} | |
} | |
/** | |
* Cast an object to another class, keeping the properties, but changing the methods | |
* | |
* @param string $class Class name | |
* @param object $object | |
* @return object | |
*/ | |
function casttoclass($class, $object) | |
{ | |
return unserialize(preg_replace('/^O:\d+:"[^"]++"/', 'O:' . strlen($class) . ':"' . $class . '"', serialize($object))); | |
} | |
$a = new mother(5); | |
$z = casttoclass('grandmother', $a); | |
echo $z->getVal(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment