PHP 中的变量、常量、关联数组
我正在开发一个小项目,需要以某种方式实施国际化支持。我正在考虑使用常量为一个文件中的文本定义许多符号,这些符号随后可以包含在内。但是,我不确定使用变量是否更快,或者我是否可以使用关联数组而不会对性能造成太大影响。
在 PHP 中定义常量值的最佳方式是使用 define("FOO", "...")
定义常量,或者使用 $foo = ".. ."
,或者像 $symbols["FOO"]
这样的关联数组?
I'm working on a small project, and need to implement internationalization support somehow. I am thinking along the lines of using constants to define a lot of symbols for text in one file, which could be included subsequently. However, I'm not sure if using variables is faster, or if I can get away with using associative arrays without too much of a performance hit.
What's better for defining constant values in PHP, performance-wise -- constants defined using define("FOO", "...")
, or simple variables like $foo = "..."
, or associative arrays like $symbols["FOO"]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能想尝试使用 Zend_Translate 和 Zend_Locale 以及您需要的任何其他组件(Zend_Date、Zend_Currency 等)。它会在文件空间方面增加应用程序的大小,但您可以轻松缓存所有翻译,并且它允许您从多种不同的翻译格式中进行选择(getext、tmx、csv、xliff 等) 。
You might want to try using Zend_Translate and Zend_Locale plus whatever other components you need (Zend_Date, Zend_Currency, etc..). Its going to beef up the size of your app in terms of filespace, but you can cache all your translations easily and it allows you to choose from a number of different fomrats for your translations (getext, tmx, csv, xliff, etc.).
性能不会有任何明显的差异,所以不用担心。做任何更容易维护的事情。
就我个人而言,如果不是太复杂的话,我会选择关联数组。如果事情稍微复杂一点,那么使用 gettext。
There's not going to be any noticeable difference in performance so don't worry about that. Do whatever is going to be easier to maintain.
Personally i'd go with an associative array if it's not too complicated. If things are a little more complicated then use gettext.
想想 gettext
这个问题与性能无关。
语法问题(即常量与变量)不会影响性能
Think of gettext
This question is not performance related.
No syntax issue (i.e. constants vs. variables) can affect performance
在编译语言中,常量由编译器替换,其常量值会影响性能和内存需求。
在 PHP 中
define
是出了名的慢。以至于有人甚至编写了一个 PHP 扩展来解决这个问题: http://pecl.php.net /package/hidef现在我想起来,这个扩展可能是您考虑国际化支持的一个不错的选择。
它允许您在单独的 ini 文件中定义常量,看起来像:
这对于非程序员(例如翻译人员)来说很容易阅读/理解
In compiled languages, constants are replaced by the compiler with their constant value affect both performance and memory requirements.
In PHP
define
is notoriously slow. So much so that somebody even wrote a PHP extension to remedy the problem: http://pecl.php.net/package/hidefNow that I think of it, this extension could a nice option to consider for you internationalization support.
It allows you to define the constants in a separate ini file, looking something like:
which is easy to read/comprehend for non-programmers (translators for example)