简体   繁体   中英

Reusing Key names (e.g. for arrays) in PHP

I'd like to use a variable or constant or something to reuse my key names for arrays to ensure that I don't have a typo inside my script.

Bad example, where I have to retype the keyname:

$var = array['keyName'];
$var2 = array['keyName'];

Now, if I change the key name I have to check all the places and replace it where necessary. My current solution is something like this:

$key = 'keyName';

$access = array[$key];

function foo($inputArray) {

// Necessary global, to access $key
global $key;

$var = $inputArray[$key];
}

But this seems kind of wrong. What would be the best way to reuse key names, while ensuring that my IDE detects all uses? I know about define(string, string), but I had problems in some cases because it didn't resolve them all the time.

This example shows where constants are not working for me:

define('requestParameterName', 'requestParam');
function checkGuess() {
    $currentGuess = strtoupper($_REQUEST['requestParameterName'] . " further concatenation");
    echo $currentGuess;
}

In the previous example, "requestParameterName" is the valid parameter name, and not "requestParam" as I would like it to be.

Using the example you just posted drop the '' in $_REQUEST['requestParameterName'] . Make it just $_REQUEST[requestParameterName] . I would use all uppercase letters in constants though, just to make it easier to read.

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