如何解决 php 中没有数组作为类常量的问题?
我有一个带有静态方法的类。有一个数组用于检查传递的字符串参数是否是集合的成员。但是,使用静态方法,我无法在未实例化的类中引用类属性,也无法将数组作为类常量。
我想我可以在静态方法中对数组进行硬编码,但是如果我需要更改它,我必须记住在两个地方更改它。我想避免这种情况。
I have a class with a static method. There is an array to check that a string argument passed is a member of a set. But, with the static method, I can't reference the class property in an uninstantiated class, nor can I have an array as a class constant.
I suppose I could hard code the array in the static method, but then if I need to change it, I'd have to remember to change it in two places. I'd like to avoid this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建一个私有静态函数,它将根据需要创建数组并返回它:
You can create a private static function that will create the array on demand and return it:
我将数组放入另一个文件中,然后在需要的地方包含该文件。
I put arrays in another file and then include the file wherever I need it.
我真的很难理解你的问题。这基本上是我的理解:
PHP 没有固定类型,甚至在 SPL 中也没有!我们可以模拟集合的功能,但我能想到的任何解决方案都不是令人愉快的。这是我认为最干净的:
示例用法:
I am having a really really hard time understanding your question. Here is essentially what I understood:
PHP does not have a set type, not even in SPL! We can emulate the functionality of a set but any solution I can think of is not pleasant. Here is what I think is the cleanest:
Example usage: