Jump to content

How to append strings to a constant's name, and then use the constant?


lordvader

Recommended Posts

Say:

define('NAME-1', 'Larry');

define('NAME-2', 'Curly');

define('NAME-3', 'Moe');

 

How could I append a number to a portion of a string and then use that new thing as a constant and not as a string?

Like: take the number 1, append it to the back of NAME- and then now php knows that I want to use constant NAME-1, and returns 'Larry', instead of returning string "NAME-1".

 

TIA

 

 

hmmm - I hope you know what constants are and what they are for...

 

The reason being is that you cant reference constants liek variables...

 

define('NAME-'.$i, 'String'); will work but I don't see how its going to be useful as you cant then do anything like

 

echo NAME-.$i;

 

So ultimately this process is pointless.

If you are setting them dynamically, they are variables, not constants.

 

Use an array.

 

<?php

$names = array (1=>'Larry', 'Curly', 'Moe');

$x = 1;

echo $names[$x];       // Larry

I meant like this:

 

function stooge($num)

$temp = 'NAME-' . $num

echo $temp

 

---

stooge(1); echoes Larry. (But of course my example func will just echo the phrase NAME-1 )

 

I want to avoid using an if else tree or a switch, like

func stooge($num)

if ($num == 1) echo NAME-1

if ($num == 2) echo NAME-2

 

or

func stooge($num)

switch ($num)

case 1: echo NAME-1

case 2: echo NAME-2

 

I don't want to change the constant's name after the fact.

TIA

like I said - you can ONLY reference constants by their full assigned 'name' you CAN NOT concatenate a string that represents the name of that constant (maybe you can with eval but thats just VERY poor programming in my book).

 

These are NOT constants so don't bother using ing them - just use variables...

You can, but I don't see the point

 

<?php
define("NAME-1", 'Curly');
define('NAME-2', 'Larry');
define('NAME-3', 'Moe');

$stooge = 1;
$var = 'NAME-'. $stooge;

echo constant($var);           //Curly

?>

face egg on :P

 

NEVER used constant(); only constants I have are configuartion settings for my apps - I know what they are called so never had any call for to reference them dynamically - you learn somethinge new everyday...

 

even if you doubt you'll ever use it ;)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.