Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic constant name in PHP

I am trying to create a constant name dynamically and then get at the value.

define( CONSTANT_1 , "Some value" ) ;  // try to use it dynamically ... $constant_number = 1 ; $constant_name = ("CONSTANT_" . $constant_number) ;  // try to assign the constant value to a variable... $constant_value = $constant_name; 

But I find that $constant value still contains the NAME of the constant, and not the VALUE.

I tried the second level of indirection as well $$constant_name But that would make it a variable not a constant.

Can somebody throw some light on this?

like image 415
vikmalhotra Avatar asked Oct 22 '10 08:10

vikmalhotra


People also ask

What is a dynamic constant?

A dynamic constant is not created by processing a literal expression but by invoking a so-called bootstrap method that produces the constant value as its result.

How do you call a constant in PHP?

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.

How can I get constant variable in PHP?

If you have defined a constant, it can never be changed or undefined. To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $.

What does dynamic mean in PHP?

A variable of a variable takes a value of a variable and threads which is the name of a variable. This is new feature of using variables and by using double dollar signs. This technique is called a dynamic variable in PHP. Those variables you can use a dynamically generated variable of variable as well as OOP Concept.


1 Answers

http://dk.php.net/manual/en/function.constant.php

echo constant($constant_name); 
like image 129
Mads Lee Jensen Avatar answered Sep 24 '22 12:09

Mads Lee Jensen