©
本文档使用 PHP中文网手册 发布
(PHP 5)
ReflectionClass::getConstructor — 获取类的构造函数
获取已反射的类的构造函数。
此函数没有参数。
一个 ReflectionMethod 对象,反射了类的构造函数,或者当类不存在构造函数时返回 NULL
。
Example #1 ReflectionClass::getConstructor() 的基本用法
<?php
$class = new ReflectionClass ( 'ReflectionClass' );
$constructor = $class -> getConstructor ();
var_dump ( $constructor );
?>
以上例程会输出:
object(ReflectionMethod)#2 (2) { ["name"]=> string(11) "__construct" ["class"]=> string(15) "ReflectionClass" }
[#1] jochem at drecomm dot nl [2011-05-13 08:13:02]
Old constructors also count as contructor:
<?php
class SomeClass {
function SomeClass($some_arg) {
}
}
$refl = new ReflectionClass('SomeClass');
var_dump($refl->isInstantiable()); // bool(true)
echo $refl->getConstructor();
?>
Some more behavior:
<?php
class SomeClass {
function funcA($arg1, $arg2) {
}
}
$refl = new ReflectionClass('SomeClass');
var_dump($refl->isInstantiable()); // bool(true)
var_dump($refl->getConstructor()); // NULL
class AnotherClass {
private function __construct() {
}
function funcB($arg1, $arg2) {
}
}
$refl = new ReflectionClass('AnotherClass');
var_dump($refl->isInstantiable()); // bool(false)
echo $refl->getConstructor();
?>
Tested on PHP 5.2.4
[#2] Rob McVey [2010-07-16 07:47:34]
Just posting some example code for anyone wanting to mess around with this stuff:
<?php
class Say
{
private $what_to_say;
public function __construct($no_default, $word = "Hello World", $options = array('a', 'b'))
{
$this->what_to_say = $word;
}
public function speak()
{
echo $this->what_to_say;
}
}
$class = new ReflectionClass('Say');
$constructor = $class->getConstructor();
echo $constructor;
$parameters = $constructor->getParameters();
var_export($parameters);
$nl = "\n";
echo "$nl\tParameters$nl";
foreach($parameters as $param)
{
echo "****** $" . $param->name . " ******$nl";
echo "Nullable:\t\t" . $param->allowsNull() . $nl
."Default Value:\t\t";
echo ($param->isDefaultValueAvailable()) ? $param->getDefaultValue() : "None";
echo $nl ."Is Array:\t\t";
echo ($param->isArray()) ? "Yes" : "No";
echo $nl . "Optional:\t\t";
echo ($param->isOptional()) ? "Yes" : "No";
echo $nl;
}
?>
To clarify the possibly confusing behavior of ReflectionParemeter::isArray(), it will return true if the parameter has type hinting:
<?php
...
public function __construct($no_default, $word = "Hello World", array $options = array('a', 'b'))
...
?>
Calling isArray() will now return true for the $options parameter