首页 > 解决方案 > PHP:静态类数组导致“使用未定义的常量”警告 - “新”关键字是适当的解决方案吗?

问题描述

我有几个静态类 , TextAttributeTypeNumberAttributeType并且ColorAttributeType我想将它们放入一个数组中,因为我需要可用类型的列表稍后是可过滤/可扩展的。

当我尝试

$available_attributes = array(
    TextAttributeType,
    NumberAttributeType,
    ColorAttributeType,
);

这会导致每个类名出现以下警告:

警告:使用未定义的常量 TextAttributeType - 假定为“TextAttributeType”

当我new在类名前面添加关键字时,它会起作用:

$available_attributes = array(
    new TextAttributeType,
    new NumberAttributeType,
    new ColorAttributeType,
);

- 但这不反对使用静态类吗?

标签: phpstatic-classes

解决方案


在您的第二个示例中,您正在实例化对象,如果您只需要一个字符串数组,您可以这样做:

$available_attributes = array(
  TextAttributeType::class,
  NumberAttributeType::class,
  ColorAttributeType::class,

);

来自 php 文档:特殊的 ::class 常量允许在编译时解析完全限定的类名,这对于命名空间类很有用。

所以你应该得到一个带有完全限定名的字符串(命名空间+类名)


推荐阅读