php - PHP:静态类数组导致“使用未定义的常量”警告 - “新”关键字是适当的解决方案吗?
问题描述
我有几个静态类 , TextAttributeType
,NumberAttributeType
并且ColorAttributeType
我想将它们放入一个数组中,因为我需要可用类型的列表稍后是可过滤/可扩展的。
当我尝试
$available_attributes = array(
TextAttributeType,
NumberAttributeType,
ColorAttributeType,
);
这会导致每个类名出现以下警告:
警告:使用未定义的常量 TextAttributeType - 假定为“TextAttributeType”
当我new
在类名前面添加关键字时,它会起作用:
$available_attributes = array(
new TextAttributeType,
new NumberAttributeType,
new ColorAttributeType,
);
- 但这不反对使用静态类吗?
解决方案
在您的第二个示例中,您正在实例化对象,如果您只需要一个字符串数组,您可以这样做:
$available_attributes = array(
TextAttributeType::class,
NumberAttributeType::class,
ColorAttributeType::class,
);
来自 php 文档:特殊的 ::class 常量允许在编译时解析完全限定的类名,这对于命名空间类很有用。
所以你应该得到一个带有完全限定名的字符串(命名空间+类名)
推荐阅读
- c# - 使用 For 循环更改组合框值
- python - R:比较两个时间序列
- linux - 将文件从 GCE VM 下载到 Windows
- c - 用 C 中的数组制作一个按字母顺序排列的字母计数器
- spring-boot - 云和本地部署的不同工件
- c# - 尝试在自定义方法的返回值上调用 ThenInclude
- arrays - SwiftUI 按 id 对自定义对象数组进行排序
- python-3.x - 映射以创建虚拟变量
- php - 在 Heroku 上使用 React js 应用程序部署 Symfony 4
- java - java.lang.NoSuchMethodError: org.hamcrest.beans.SamePropertyValuesAs.isNotNull(Ljava/lang/Object;Lorg/hamcrest/Description;)