简体   繁体   English

在PHP中实现数据结构的最佳方法?

[英]Best way to implement a data structure in PHP?

I want to use some kind of data structure in PHP (5.2), mainly in order to not pollute the global namespace. 我想在PHP(5.2)中使用某种数据结构,主要是为了不污染全局名称空间。 I think about two approaches, using an array or a class. 我考虑两种方法,使用数组或类。 Could you tell me which approach is better ? 你能告诉我哪种方法更好吗?

Also, the main purpose would be for storing configurations constants. 同样,主要目的是存储配置常量。

Thanks 谢谢

$SQL_PARAMETERS = array (
    'server' => '127.0.0.1',
    'login'  => 'root');

class SqlParameters {
    const SERVER = '127.0.0.1';
    const LOGIN  = 'root';
}

echo $SQL_PARAMETERS['server'];
echo SqlParameters::SERVER;

I'd say that class approach is better because you won't overwrite const or the whole class by accident. 我想说使用类方法更好,因为您不会偶然覆盖const或整个类。 And you can also extend your class with some methods should you need them later on. 而且,如果以后需要它们,您还可以使用一些方法扩展您的类。

除非您要创建方法和多个实例,否则数组就可以了。

You said you want to avoid polluting your global namespace yet creating an array will do just that: create a global variable that you will be forced to call inside of your classes. 您说过要避免污染全局名称空间,但是创建一个数组可以做到这一点:创建一个全局变量,您将不得不在类内部调用它。 This is not best practice and you should strive to avoid global variables at all costs. 这不是最佳做法,您应不惜一切代价避免全局变量。 The class example you posted in your question would be the acceptable solution, also for the reasons that RaYell pointed out. 出于RaYell指出的原因,您在问题中发布的课堂示例将是可接受的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM