php isinstantiable,PHP: ReflectionClass::isInstantiable - Manual

An example missing from the documentation is that `ReflectionClass::isInstantiable` will also return false for traits, as well as interfaces and abstract classes.

<?phptraitt {// Optional trait methods and properties etc.}$reflectionClass= newReflectionClass("t");var_dump($reflectionClass->isInstantiable());// bool(false)?>

As for classes with private constructors, it is still possible to create an instance by either bypassing the constructor using `ReflectionClass::newInstanceWithoutConstructor`, or by ensuring the class has a method which can create a new instance.

private function__construct() {// Optional constructor logic - not called when ReflectionClass::newInstanceWithoutConstructor is used.}

public static functioncreate() {

return newp;

}// Optional methods and properties etc.}// Class is not classed as instantiable.$reflectionClass= newReflectionClass("p");var_dump($reflectionClass->isInstantiable());// bool(false)

// We're still able to create an instance using one of the two methods.$p=p::create();$p=$reflectionClass->newInstanceWithoutConstructor();?>

The same is also true for protected constructors, however, the class can be instantiated from either parent or child methods, depending on where the constructor is defined.

protected function__construct() {// Optional constructor logic.}

public static functioncreate($class="") {

if (!$class) {$class=get_called_class();

}

return new$class;

}// Optional parent methods and properties etc.}

classcextendsp{// Optional child methods and properties etc.}// Both child and parent static methods have access to each other's protected constructor.$p=c::create("p");$c=p::create("c");// Both are still not classed as being instantiable.$reflectionClassP= newReflectionClass("p");$reflectionClassC= newReflectionClass("c");var_dump($reflectionClassP->isInstantiable());// bool(false)var_dump($reflectionClassC->isInstantiable());// bool(false)

// We're still able to bypass the constructor and create an instance for each.$p=$reflectionClassP->newInstanceWithoutConstructor();$c=$reflectionClassC->newInstanceWithoutConstructor();?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值