My Blog

PHP Variable Variables and Variable Constants

6.17.2012 | Blog, PHP

In this small article I’ll illustrate PHP’s variable variables and Variable constants. There is no variable constants in PHP but I’m introducing a methodology to implement the same approach and achieve the same functionality as variable variables.

As you may know that you can have a variable variable like the following:

$who = 'world';
$world = 'World!';
$people = 'People!';
echo 'Hello ' . $$who;
// output: Hello World!

Where the variable name here becomes $world as the value of $who, if we changed the value of $who to be ‘people’, in the last line it will load the variable $people.

$who = 'people';
$world = 'World!';
$people = 'People!';
echo 'Hello ' . $$who;
// output: Hello People!

What if you want to have a variable constant? I mean like you want to lookup a name of a constant dynamically.

Suppose we have got the following constants:

define('PAYPAL_MIN_AMOUNT',5); // minimum amount of payment for paypal method
define('CREDIT_CARD_MIN_AMOUNT',30); // minimum amount of payment for credit card method

Now we want to dynamically validate the submitted amount against the minimum amount according to the payment method.

The submitted value is either PAYPAL or CREDIT_CARD
we can do the following:

// suppose this was the submitted value
$paymentMethod='PAYPAL';
echo "Minimum amount for {$paymentMethod} is " . constant($paymentMethod.'_MIN_AMOUNT') . ' USD';
// output: Minimum amount for PAYPAL is 5 USD
$paymentMethod='CREDIT_CARD';
echo "Minimum amount for {$paymentMethod} is " . constant($paymentMethod.'_MIN_AMOUNT') . ' USD';
// output: Minimum amount for CREDIT_CARD is 30 USD

We made use of the constant() php standard function to call a variable constant name. Which returns the value of a given constant name.

Happy programming :)

Be Sociable, Share!

Responses

Nate Ferrero
11.08.2012

Awesome, I hadn’t heard of the constant() function :)

Comments