PHP: Hypertext Preprocessor (original) (raw)

ReflectionClass::isInstantiable

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isInstantiable — Checks if the class is instantiable

Description

public ReflectionClass::isInstantiable(): bool

Parameters

This function has no parameters.

Return Values

Returns [true](reserved.constants.php#constant.true) on success or [false](reserved.constants.php#constant.false) on failure.

Examples

Example #1 ReflectionClass::isInstantiable() example

`<?php
class C { }

interface

iface {
function f1();
}

class

ifaceImpl implements iface {
function f1() {}
}

abstract class

abstractClass {
function f1() { }
abstract function f2();
}

class

D extends abstractClass {
function f2() { }
}

trait

T {
function f1() {}
}

class

privateConstructor {
private function __construct() { }
}$classes = array(
"C",
"iface",
"ifaceImpl",
"abstractClass",
"D",
"T",
"privateConstructor",
);

foreach( classesasclasses as classesasclass ) { reflectionClass=newReflectionClass(reflectionClass = new ReflectionClass(reflectionClass=newReflectionClass(class);
echo "Is $class instantiable? ";
var_dump($reflectionClass->isInstantiable());
}?>`

The above example will output:

Is C instantiable? bool(true) Is iface instantiable? bool(false) Is ifaceImpl instantiable? bool(true) Is abstractClass instantiable? bool(false) Is D instantiable? bool(true) Is T instantiable? bool(false) Is privateConstructor instantiable? bool(false)

Found A Problem?

shaun at slickdesign dot com dot au

7 years ago

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

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.

isInstantiable()); // bool(false) // We're still able to create an instance using one of the two methods. $p = p::create(); p=p = 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.

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

``