【发布时间】:2012-12-13 07:15:53
【问题描述】:
可能重复:
Accessing a class constant using a simple variable which contains the name of the constant
作为静态调用的结果,我想使用反射来发送一个 const 数组
class ArrowType extends AbstractAttributeType
{
const NORMAL = 'normal';
const INV = 'inv';
static function getPossibleValues()
{
$refl = new \ReflectionClass(__CLASS__);
$class_vars = $refl->getConstants();
$res = array();
foreach ($class_vars as $name => $value) {
$res[] = static::$$name;
}
return $res;
}
}
这给了我
致命错误:访问未声明的静态属性:ArrowType::$NORMAL
我想买
ArrowType::NORMAL
当调用$arrowType->getPossibleValues()
编辑
为了让我的问题更容易理解,我将给你详细说明。 我正在使用https://github.com/yethee/BiplaneEnumBundle,我正在努力让我的生活更轻松。目前,我必须生成以下代码才能满足库要求。
class ArrowType extends AbstractAttributeType
{
const NORMAL = 'normal';
const INV = 'inv';
const DOT = 'dot';
const INVDOT = 'invdot';
const ODOT = 'odot';
const INVODOT = 'invodot';
const NONE = 'none';
static function getPossibleValues()
{
return array(
static::NORMAL,
static::INV,
static::DOT,
static::INVDOT,
static::ODOT,
static::INVODOT,
static::NONE
);
}
static function getReadables()
{
return array(
static::NORMAL => 'normal',
static::INV => 'inv',
static::DOT => 'dot',
static::INVDOT => 'invdot',
static::ODOT => 'odot',
static::INVODOT => 'invodot',
static::NONE => 'none'
);
}
}
我现在想要实现的是在两个函数中动态构建数组,以便将这些函数放在父类中,并在我的类中声明 const 部分。我希望这能帮助好心的读者理解我想要什么。
【问题讨论】:
-
虽然这最终是解决方案,但我不确定它是否足够接近成为骗子。
-
当然,让我们也考虑到问题本身的答案:
$res[] = $value;或$res = array_values($refl->getConstants());- 使用反射时,一切都已经存在了。 -
啊哈哈,我才意识到。
-
是的,这个问题不是很清楚。也许 Mylen 可以阐明真正的问题是什么?
-
真好笑(啊啊)我的帖子被篡改了,标题被改了!我的问题是关于惰性静态绑定!对你来说可能还不够清楚,但是当你执行上面的代码时,你会得到一个错误,我想要的在最后一段的块引用中解释了
标签: php reflection