作为字符串的PHP类名称

问题描述:

是否有内置的静态方法或属性来引用PHP类,以便它将上下文表示为字符串?例如:作为字符串的PHP类名称

取而代之的是:

$obj->tempFn('MyClass') //MyClass being the name of the class 

我想这样做:

$obj->tempFn(MyClass) //Directly references the class name, instead of a string representation 
+0

$ obj-> tempFn(新MyClass的()) 或 $ MyClass的=新MyClass的(); //用这个对象做点什么 $ obj-> tempFn($ myClass); – sanj 2013-02-20 16:33:05

+0

请注意,新的MyClass()会创建类MyClass的一个实例,它与对类的引用不一样。但是,为什么你需要这样做呢? – cernunnos 2013-02-20 16:34:43

+0

请解释你的意思是“上下文被表示为一个字符串”。你想要做什么?这个问题可以用几种方式解释。 – 2013-02-20 16:36:11

不可以,但你可以在你的类,包含类的名称,如定义一个常量:

class foo{ 
    const 
    NAME = 'foo'; 
} 

,并获得它像foo::NAME

PHP 5.5,你就可以使用:

foo::class 
+1

这是我要采取的方法,但我想确保没有更好的方法。惊讶它不是已经可用。谢谢! – astonius 2013-02-20 16:44:01

echo get_class($this);应的类的内部工作。

echo __CLASS__;我相信这是一个静态属性

+0

谢谢,但是我需要在课堂之外引用它,并且不要首先实例化这个类。 – astonius 2013-02-20 16:35:00

+0

你可以返回' _静态方法中的__CLASS__'属性(即静态函数getName())? – Husman 2013-02-20 16:37:58

+0

@astonius这是一个玩笑吗?如果你没有实例化类,你只能通过静态方法和变量来访问它。类似'Math :: sum()'。只需手工写'echo'Math''?? – vikingmaster 2013-02-20 16:38:40

如果真的想避开我觉得思考类可能的工作静态。

function getClassName(ReflectionParameter $param) { 
    preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches); 
    return isset($matches[1]) ? $matches[1] : null; 
} 

从评论对http://www.php.net/manual/en/reflectionparameter.getclass.php