0

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.

1
  • 1
    Why would you want to do that anyway? TITLE_1 is as meaningless as TITLE_2. Passing 1 or 2 to getTitle() is not helping anyone to understand what these Magic Numbers stand for. Either you want to use Constants, then access them directly with TITLE_YAHOO or TITLE_GOOGLE or use Contant Methods instead of the Constants, e.g. getTitleForYahoo() and getTitleForGoogle() where those return the strings. But not that mishmash. Commented Mar 31, 2011 at 9:17

4 Answers 4

7

Use the constant function

public function title($id) {
    return constant("TITLE_$id");
}
Sign up to request clarification or add additional context in comments.

2 Comments

TITLE_.$id should be quoted. otherwise PHP notice will be there.
Notice: Use of undefined constant TITLE_ - assumed 'TITLE_' in Command line code on line 1 --- You should use "TITLE_$id"
4

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.

Comments

1

you need to return constant(TITLE_.$id)

edited

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

Thanks Gaurav

1 Comment

TITLE_.$id should be quoted. otherwise PHP notice will be there.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.