[英]Adding variable to constant, php
I have defined a few constants like this: 我定义了一些这样的常量:
define("TITLE_2","Yahoo");
define("TITLE_3","Google");
Next, I want to get the constant through a function. 接下来,我想通过函数获取常量。
public function title($id) {
return TITLE_.$id;
}
Idea, I can call $this->title(2) to get Yahoo and $this->title(3) to get Google. 想法,我可以调用$ this-> title(2)来获取Yahoo,并调用$ this-> title(3)来获取Google。 However, it is not working. 但是,它不起作用。 I am getting TITLE_2 or TITLE_3 in place of Yahoo or Google. 我正在使用TITLE_2或TITLE_3代替Yahoo或Google。
Help? 救命? Thanks. 谢谢。
What php is trying to do here is "get the define TITLE_
and then append the value stored in $id". PHP在这里试图做的是“获取定义TITLE_
,然后附加存储在$ id中的值”。
You need to use the constant()
function for this to work like you want: 您需要使用constant()
函数来使其按需工作:
public function title($id) {
return constant("TITLE_$id");
}
Using the way you decribed also produces and 使用您描述的方式还会产生和
Notice: Use of undefined constant TITLE_ - assumed 'TITLE_' 注意:使用未定义的常量TITLE_-假定为“ TITLE_”
Make sure you have error reporting turned on and at least enabled E_NOTICE
warnings as they will help you a lot when debugging things like this. 确保已打开错误报告并至少启用了E_NOTICE
警告,因为它们在调试此类内容时会为您提供很多帮助。
you need to return constant(TITLE_.$id)
您需要return constant(TITLE_.$id)
edited 已编辑
you need to `return constant("TITLE_.$id")`
Thanks Gaurav 谢谢高拉夫
也许您可以使用get_defined_constants()来获取常量列表,然后选择所需的常量...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.