note 106657 added to reflectionclass.newinstancewithoutconstructor
| From: | oliver at ananit dot de | Date: | Thu, 24 Nov 2011 23:57:35 +0000 |
| Subject: | note 106657 added to reflectionclass.newinstancewithoutconstructor | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-184669@lists.php.net to get a copy of this message | ||
If this method is not available in your version of PHP you can use a trick to create an instance
without calling the constructor.
Use reflection to get the properties and default values of the class, and create a fake
"serialized" string.
<?php
function createInstanceWithoutConstructor($class){
$reflector = new ReflectionClass($class);
$properties = $reflector->getProperties();
$defaults = $reflector->getDefaultProperties();
$serealized = "O:" . strlen($class) .
":\"$class\":".count($properties) .':{';
foreach ($properties as $property){
$name = $property->getName();
if($property->isProtected()){
$name = chr(0) . '*' .chr(0) .$name;
} elseif($property->isPrivate()){
$name = chr(0) . $class. chr(0).$name;
}
$serealized .= serialize($name);
if(array_key_exists($property->getName(),$defaults) ){
$serealized .= serialize($defaults[$property->getName()]);
} else {
$serealized .= serialize(null);
}
}
$serealized .="}";
return unserialize($serealized);
}
?>
Example:
<?php
class foo
{
public $a = 10;
protected $b = 2;
private $c = "default";
protected $d;
public function __construct(){
$this->a = null;
$this->b = null;
$this->c = "constructed";
$this->d = 42;
}
}
var_dump(createInstanceWithoutConstructor('foo'));
?>
Output:
object(foo)#6 (4) {
["a"]=>
int(10)
["b":protected]=>
int(2)
["c":"foo":private]=>
string(7) "default"
["d":protected]=>
NULL
}
I hope this can help someone.
Oliver Anan
----
Server IP: 69.147.83.197
Probable Submitter: 88.65.40.241
----
Manual Page -- http://www.php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php
Edit -- https://master.php.net/note/edit/106657
Del: integrated -- https://master.php.net/note/delete/106657/integrated
Del: useless -- https://master.php.net/note/delete/106657/useless
Del: bad code -- https://master.php.net/note/delete/106657/bad+code
Del: spam -- https://master.php.net/note/delete/106657/spam
Del: non-english -- https://master.php.net/note/delete/106657/non-english
Del: in docs -- https://master.php.net/note/delete/106657/in+docs
Del: other reasons-- https://master.php.net/note/delete/106657
Reject -- https://master.php.net/note/reject/106657
Search -- https://master.php.net/manage/user-notes.php