Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection in namespace php

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

$reflect=new \ReflectionClass('a');
$properties=$reflect->getProperties(ReflectionProperty::IS_PROTECTED);

It will return ReflectionProperty class not found Fatal error Where $properties is array of object of ReflectionProperty. Why does not it resolved to global space automatically? where as DOM related class do that implicitly. if ReflectionProperty class is used in namespace it works though. but why not implicitly it happends?

like image 208
varuog Avatar asked Aug 08 '12 07:08

varuog


2 Answers

class in namespace will be preceeded by namespace name and global property needs to be preceeded by slash(\). use manual Try this

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

$reflect=new \ReflectionClass('\\foo\\a');
$properties=$reflect->getProperties(\ReflectionProperty::IS_PROTECTED);
like image 114
Poonam Avatar answered Sep 21 '22 14:09

Poonam


Relative classnames (those not starting with \\) are always resolved first against the current namespace and then against every aliased identifier (via use). This means especially, that if you don't define a concrete namespace yourself you are within the global one, which means, that \Bar and Bar refers the same class. But if you are within a namespace Foo they differs (\Bar <==> Bar == \Foo\Bar).

You can find a detailed explanation in the manual. In the "namespace basics" section of the manual you can find the idea behind this: It's like a filesystem. If you are in the root, cat /etc/passwd and cat etc/passwd are the same, but not, if you change the workdirectory.

(Beside: It should be $reflect=new \ReflectionClass('\\foo\\a');, or $reflect=new \ReflectionClass(__NAMESPACE__ . '\\a');)

like image 37
KingCrunch Avatar answered Sep 19 '22 14:09

KingCrunch