phpconstantsconstant-expression

How to use a $variable as the value in a constant declaration


Suppose I have the following code which prints out an item price statically as shown below:

define ("itemprice1", "20");

How do I correctly replace the number 20 with $price variable name inside the double quotes?

I tried define ("itemprice1", ".$price."); but as you may have already guessed, it just printed out .$price. in plain text.


Solution

  • Use

    define ("itemprice1", (string) $price);
    

    Note: Define the constant name as UPPERCASE is better for readability. eg define ("ITEMPRICE1", (string) $price);

    Edit:

    use

    define ("ITEMLINK1", "item.php?id=" . $price);