<?php
$classNames = array(
"Foo", // userland class
"StdClass", // class defined by php-src, but still not considered as internal
"Bar", // userland class implementing Serializable
"ReflectionClass", // internal class
"ArrayObject", // internal class implementing Serializable
"Baz", // userland class extending internal class implementing Serializable
);
function instanitateWithoutConstructorThroughUnserialize($className) {
$class = new ReflectionClass($className);
return unserialize(
sprintf(
'%s:%d:"%s":0:{}',
(version_compare(PHP_VERSION, '5.4', '>') && $class->implementsInterface("Serializable") ? "C" : "O"),
strlen($className),
$className
)
);
}
function instanitateWithoutConstructorThroughReflection($className) {
try {
$ref = new ReflectionClass($className);
return $ref->newInstanceWithoutConstructor();
} catch (ReflectionException $e) {
return $e;
}
}
class Foo {}
class Bar implements Serializable {
private $data;
public function serialize() {
return serialize($this->data);
}
public function unserialize($data) {
$this->data = unserialize($data);
}
}
class Baz extends ArrayObject {}
foreach($classNames as $className) {
echo "$className\n";
var_dump(instanitateWithoutConstructorThroughUnserialize($className));
if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
var_dump(instanitateWithoutConstructorThroughReflection($className));
}
echo "\n";
}