简体   繁体   中英

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. However, it is not working. I am getting TITLE_2 or TITLE_3 in place of Yahoo or Google.

Help? Thanks.

Use the constant function

public function title($id) {
    return constant("TITLE_$id");
}

What php is trying to do here is "get the define TITLE_ and then append the value stored in $id".

You need to use the constant() function for this to work like you want:

public function title($id) {

    return constant("TITLE_$id");
}

Using the way you decribed also produces and

Notice: Use of undefined constant TITLE_ - assumed '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.

you need to return constant(TITLE_.$id)

edited

you need to `return constant("TITLE_.$id")`

Thanks Gaurav

也许您可以使用get_defined_constants()来获取常量列表,然后选择所需的常量...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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