为什么序列化对象不能存储在 const 常量中?
<?php
const FOOBAR = "Foo"; // Works.
const FOOBAR = array("Foo", "Bar"); // Doesn't work. Makes sense.
const FOOBAR = serialize(array("Foo", "Bar")); // Doesn't work. Okay. :\
define("FOOBAR", serialize(array("Foo", "Bar"))); // Works! The heck?
?>
PHP 解析错误:语法错误、意外的 '('、期望 ',' 或 ';'
为什么使用 define() 声明常量时可以将常量设置为序列化对象
,但不使用 const
关键字?
(使用 5.3.5-1ubuntu7.2
进行测试。)
<?php
const FOOBAR = "Foo"; // Works.
const FOOBAR = array("Foo", "Bar"); // Doesn't work. Makes sense.
const FOOBAR = serialize(array("Foo", "Bar")); // Doesn't work. Okay. :\
define("FOOBAR", serialize(array("Foo", "Bar"))); // Works! The heck?
?>
PHP Parse error: syntax error, unexpected '(', expecting ',' or ';'
Why can constants be set to serialized objects when they're declared with define()
, but not with the const
keyword? What am I missing here?
(Tested with 5.3.5-1ubuntu7.2
.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
const 只能采用标量或非表达式值。
Define 将采用表达式值,这就是 Define 在您的情况下起作用的原因。
const can only take scalar or non expressions values.
define will take expressions values and that is why define works in your case.
const 是编译时操作。定义是一个运行时操作。更多的 php 机制,包括数组分配和空间分配,在运行时可用。
相关的SO问题
Google php const Define
了解更多信息
const is a compile-time action. define is a run-time action. More php machinery including array allocation and space allocation is available at runtime.
A related SO question
Google php const define
for more