Jeremy Roy
Jeremy Roy

Reputation: 1291

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.

Upvotes: 0

Views: 2545

Answers (4)

Rob Agar
Rob Agar

Reputation: 12447

Use the constant function

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

Upvotes: 7

edorian
edorian

Reputation: 38961

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.

Upvotes: 4

J Bourne
J Bourne

Reputation: 1429

you need to return constant(TITLE_.$id)

edited

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

Thanks Gaurav

Upvotes: 1

Softy
Softy

Reputation: 542

Maybe you could use the get_defined_constants() to get the list of the constants and then pick the one you want...

Upvotes: 0

Related Questions