简体   繁体   中英

define constant using if isset

I have an array of constants I'm using to populate an array of params. The code looks something like this:

define( 'variable_one', $_POST["variable_one"];
define( 'variable_two', $_POST["variable_two"];

$current_api_params->sVariableOne = variable_one;
$current_api_params->sVariabletwo = variable_two;

How do I set one of the constants through an if statement? The variables are coming from a form, and given the form options, variable_one, or two or any of the dozens I'm working with, might be a number of different names.

Do I just do something like

if ( isset($_POST["variable_one"] ) {
  define( 'variable_one', $_POST["variable_one"] );
}
elseif ( isset($_POST["variable_one_different_name"] ) {
  define( 'variable_one', $_POST["variable_one_different_name"] );
}
else {
  define( 'variable_one', '' );
}

$current_api_params->sVariableOne = variable_one;

If that's how it is done, is there a shorthand for it? All this typing is getting tedious!

You can use array_keys and for loop

Somewhere along these lines (you might need to check some syntax error, as I'm typing this without any IDE/proper environment)

$keys = array_keys($_POST)
foreach ($keys as $keyItem)
{
    define($keyItem, $_POST[$keyItem]);
}

Though I'm not sure why constants are not constant at all ... but hey that's up to you to decide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM