php 构造函数返回值,PHP 获取类的构造函数

Just posting some example code for anyone wanting to mess around with this stuff:

private$what_to_say;

public function__construct($no_default,$word="Hello World",$options= array('a','b'))

{$this->what_to_say=$word;

}

public functionspeak()

{

echo$this->what_to_say;

}

}$class= newReflectionClass('Say');$constructor=$class->getConstructor();

echo$constructor;/*     OUTPUTS:

Method [  public method __construct ] {

@@ /reflect.php 6 - 9

- Parameters [3] {

Parameter #0 [  $no_default ]

Parameter #1 [  $word = 'Hello World' ]

Parameter #2 [  $options = Array ]

}

}

*/$parameters=$constructor->getParameters();var_export($parameters);/*    OUTPUT:

array (

0 =>

ReflectionParameter::__set_state(array(

'name' => 'no_default',

)),

1 =>

ReflectionParameter::__set_state(array(

'name' => 'word',

)),

2 =>

ReflectionParameter::__set_state(array(

'name' => 'options',

)),

)

*/$nl="\n";

echo"$nl\tParameters$nl";

foreach($parametersas$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;

}/*    OUTPUT:

Parameters

****** $no_default ******

Nullable:        1

Default Value:    None

Is Array:        No

Optional:        No

****** $word ******

Nullable:        1

Default Value:    Hello World

Is Array:        No

Optional:        Yes

****** $options ******

Nullable:        1

Default Value:    Array

Is Array:        No

Optional:        Yes

*/?>

To clarify the possibly confusing behavior of ReflectionParemeter::isArray(), it will return true if the parameter has type hinting:

public function__construct($no_default,$word="Hello World", array$options= array('a','b'))

...?>

Calling isArray() will now return true for the $options parameter

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值