简体   繁体   中英

how to use php 5 global variables as function arguments?

I have a very very simple function:

function pro_echo ($type, $key) {
    echo $type[$key];
}

for example i want to run pro_echo('$_POST', 'my_post_val') and i expect $_POST['my_post_val'] to be echo

but I encounter ''Illegal string offset'' error:

pro_echo('$_POST', 'my_post_val')

Your arguments are 2 strings because of the quotes around them. Try

pro_echo($_POST, 'my_post_val');

I don't know why you need this function, but what you need here is variable variable :

function pro_echo ($type, $key) {
    echo ${$type}[$key];
}
// and call it: note NO `$`!
pro_echo ('_POST', 'foo');
pro_echo ('_GET', 'bar');

But I suppose it is better to use function as:

function pro_echo ($value) {
    echo $value; // modify echo as you need
}
// and call it:
pro_echo ($_POST['foo']);
pro_echo ($_GET['bar']);

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