我如何实例化一个具有私有构造函数的类.
我不想在类中使用任何函数来创建自己的实例.
Ex类是:
class Test extends Test2 implements Test3 {
private function __construct () {
}
function doDisplay() {
}
function Docall() {
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Reflection实例化它(PHP> = 5.4)
class Test {
private $a;
private function __construct($a)
{
$this->a = $a;
}
}
$class = new ReflectionClass(Test::class);
$constructor = $class->getConstructor();
$constructor->setAccessible(true);
$object = $class->newInstanceWithoutConstructor();
$constructor->invoke($object, 1);
Run Code Online (Sandbox Code Playgroud)
它可以工作,但请记住,这不是该类设计的目的,并且可能会有一些无法预料的副作用。
您不能从类本身内的任何地方调用私有构造函数,因此您必须使用外部可访问的静态方法来创建实例.
此外,如果Test2有一个非私有的构造函数,你不能Test::__construct()私有.
您无法从构造函数为private(从教学大纲开始)的类中实例化对象.
如果您打算使用它的功能,那么您应该将它们作为static并使用它们来满足您的需求.确保该功能是公开的.
例如:
<?php
class something
{
private function __construct()
{
echo "something";
}
public static function display($msg)
{
echo $msg;
}
}
something::display("Testing...");
?>
Run Code Online (Sandbox Code Playgroud)
请参阅工作示例:http://codepad.org/VoYeyk8W
| 归档时间: |
|
| 查看次数: |
3360 次 |
| 最近记录: |