命名空间php中的反射

var*_*uog 8 php reflection namespaces

namespace foo;
class a
{
private $bar;
public $baz;
protected $alpha
}

$reflect=new \ReflectionClass('a');
$properties=$reflect->getProperties(ReflectionProperty::IS_PROTECTED);
Run Code Online (Sandbox Code Playgroud)

它将返回ReflectionProperty未找到的类致命错误其中$ properties是对象的数组ReflectionProperty.为什么它不能自动解决全球空间?与DOM相关的类隐含地执行此操作.如果ReflectionPropertyclass use在命名空间中是d,那么它可以工作.但为什么不隐含地发生呢?

小智 14

命名空间中的类将以命名空间名称开头,全局属性需要以斜杠(\)开头.使用手册 试试这个

namespace foo;
class a
{
private $bar;
public $baz;
protected $alpha;
}

$reflect=new \ReflectionClass('\\foo\\a');
$properties=$reflect->getProperties(\ReflectionProperty::IS_PROTECTED);
Run Code Online (Sandbox Code Playgroud)