我正在尝试获得$bar变量类型。
<?php
class Foo
{
public function test(stdClass $bar, array $foo)
{
}
}
$reflect = new ReflectionClass('Foo');
foreach ($reflect->getMethods() as $method) {
foreach ($method->getParameters() as $num => $parameter) {
var_dump($parameter->getType());
}
}我期待stdClass,但我得到
Call to undefined method ReflectionParameter::getType()有什么不对的?还是有别的办法?.
$ php -v
PHP 5.4.41 (cli) (built: May 14 2015 02:34:29)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend TechnologiesUPD1它也应该适用于数组类型。
发布于 2016-03-28 17:46:32
看起来类似的问题已经在PHP反射-获取方法参数类型作为字符串中添加了
我写了我的解决方案--它适用于所有情况:
/**
* @param ReflectionParameter $parameter
* @return string|null
*/
function getParameterType(ReflectionParameter $parameter)
{
$export = ReflectionParameter::export(
array(
$parameter->getDeclaringClass()->name,
$parameter->getDeclaringFunction()->name
),
$parameter->name,
true
);
return preg_match('/[>] ([A-z]+) /', $export, $matches)
? $matches[1] : null;
}发布于 2016-03-28 17:50:09
如果您只键入提示类,则可以使用PHP5和7中支持的->getClass()。
<?php
class MyClass {
}
class Foo
{
public function test(stdClass $bar)
{
}
public function another_test(array $arr) {
}
public function final_test(MyClass $var) {
}
}
$reflect = new ReflectionClass('Foo');
foreach ($reflect->getMethods() as $method) {
foreach ($method->getParameters() as $num => $parameter) {
var_dump($parameter->getClass());
}
}我之所以说类,是因为在数组上,它将返回NULL。
object(ReflectionClass)#6 (1) {
["name"]=>
string(8) "stdClass"
}
NULL
object(ReflectionClass)#6 (1) {
["name"]=>
string(7) "MyClass"
}https://stackoverflow.com/questions/36267390
复制相似问题