PHP 数组键在常量中
我有一个希望很快的问题。 我已将数组放置在常量中,但是当我添加数组键时,它会崩溃。我的代码如下。
<?php define("my_const_arr", serialize(array("page_ids" => array("1234", "4123")))); ?>
<?php $page_id = "4123"; ?>
<?php if(in_array($page_id, unserialize(my_const_arr["page_ids"]))): ?>
<h1>Hello Stackoverflow</h1>
<?php endif; ?>
I have a hopefully quick question.
I have placed an array in a constant but when I add array keys it craps out. My code below.
<?php define("my_const_arr", serialize(array("page_ids" => array("1234", "4123")))); ?>
<?php $page_id = "4123"; ?>
<?php if(in_array($page_id, unserialize(my_const_arr["page_ids"]))): ?>
<h1>Hello Stackoverflow</h1>
<?php endif; ?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
此时您无法执行
my_const_arr["page_ids"]
因为它仍然是一个字符串。您应该先将其反序列化,然后再访问它You can't do
my_const_arr["page_ids"]
at that point because it's still a string. You should unserialize it first and then access it您同时使用 unserialize 和 PHP 有点错误:
我还想指出,常量在您可以控制的应用程序中并不是特别有用。特别是如果该代码与您的应用程序非常相关。
这样做不会带来太多开销。我认为经常调用序列化/反序列化会给你带来不需要的处理。
发布您的确切场景,可能会提供更好的解决方案。
You're using both unserialize and PHP mildly wrong:
I would also like to point out that constants aren't particularly useful in an application you can control. Especially if that code is very relevant to your app.
You will not get much overhead by doing this. I'd think that calling serialize/unserialize often would give you unwanted processing.
Post your exact scenario and a better solution might be made available.
改成这样
Change it that way
'my_const_arr' 是一个常量,而不是一个数组。
因此,
my_const_arr["page_ids"]
不正确。也许你可以尝试这个:
'my_const_arr' is a constant, not an array.
So,
my_const_arr["page_ids"]
is incorrect.Maybe you can try this:
如果没有真正需要字符串转换,为什么不使用简单的类作为常量值的容器,例如:
编辑:抱歉,只是留下一个工作方法:
在外面你可以像这样访问它
If there's no real need for the string-conversion, why not use a simple class as a container for constant values, like:
EDIT: Sorry, just to leave a working approach:
Outside you can access it like