Amir Forsati
Amir Forsati

Reputation: 5988

making dynamic defined constants php

look at this syntax of variable name modifying:

${'a' . 'b'} = 'hello there';
echo $ab;

this returns "hello there"

But i want do declare defined variables dynamical.

$error_code = $_GET[error_code]; //for example: 404
define(E404, 'Not found');
echo E{$error_code};

It return error, i want to generate E404 dynamical on php codes and get its value. I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research.

Upvotes: 1

Views: 2411

Answers (3)

Nadir Latif
Nadir Latif

Reputation: 3773

Well Php has a feature called variable variables. See this link: http://php.net/manual/en/language.variables.variable.php. It allows a variable name to be assigned to a variable.

Upvotes: 1

Nathan Leadill
Nathan Leadill

Reputation: 114

<?php
    $ErrorCode = $_GET['error_code']; // Where error_code = 404
    $Errors = array(); // here we are creating a new array.
    $Errors[$ErrorCode] = "Whatever"; // here we are setting a key of the new array, with the keys name being equal to the $ErrorCode Variable

    print_r($Errors); // Would return Array( [404] => Whatever);

    echo $Errors["404"]; // Would return Whatever

?>

Upvotes: 1

motanelu
motanelu

Reputation: 4025

You need to call constant() to retrieve the value of a constant from a string. Your example should look like:

$error_code = 404;
define('E404', 'Not found');
echo constant("E{$error_code}");

and it will display Not found.

Upvotes: 6

Related Questions