Skip to content

Instantly share code, notes, and snippets.

@jasny
Created March 28, 2012 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasny/2223675 to your computer and use it in GitHub Desktop.
Save jasny/2223675 to your computer and use it in GitHub Desktop.
Class casting in PHP (very dirty, not for production)
<?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