note 118297 added to reflectionclass.newinstanceargs
| From: | kirillsaksin at no-spam dot yandex dot ru | Date: | Tue, 10 Nov 2015 17:59:13 +0000 |
| Subject: | note 118297 added to reflectionclass.newinstanceargs | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-204134@lists.php.net to get a copy of this message | ||
Hack to properly instantiate class with private constructor:
<?php
class TestClass
{
private $property;
private function __construct($argument)
{
$this->property = $argument;
}
}
$ref = new ReflectionClass(TestClass::class);
$instance = $ref->newInstanceWithoutConstructor();
var_dump($instance);
echo PHP_EOL . '------------------------' . PHP_EOL . PHP_EOL;
$constructor = $ref->getConstructor();
$constructor->setAccessible(true);
$constructor->invokeArgs($instance, ['It works!']);
var_dump($instance);
// Output:
// class TestClass#3 (1) {
// private $property =>
// NULL
// }
//
// ------------------------
//
// class TestClass#3 (1) {
// private $property =>
// string(9) "It works!"
// }
?>
----
Server IP: 72.52.91.14
Probable Submitter: 91.210.4.1
----
Manual Page -- http://php.net/manual/en/reflectionclass.newinstanceargs.php
Edit -- https://master.php.net/note/edit/118297
Del: integrated -- https://master.php.net/note/delete/118297/integrated
Del: useless -- https://master.php.net/note/delete/118297/useless
Del: bad code -- https://master.php.net/note/delete/118297/bad+code
Del: spam -- https://master.php.net/note/delete/118297/spam
Del: non-english -- https://master.php.net/note/delete/118297/non-english
Del: in docs -- https://master.php.net/note/delete/118297/in+docs
Del: other reasons-- https://master.php.net/note/delete/118297
Reject -- https://master.php.net/note/reject/118297
Search -- https://master.php.net/manage/user-notes.php