您好我想创建一个函数,我可以在其中传递变量并输出变量的名称及其值作为sting。像这样:
$firstname = 'John';
$lastname = 'Doe';
echo my_function($firstname); // outputs: "Var name: firstname , has: John"
echo my_function($lastname); // outputs: "Var name: lastname , has: Doe"
答案 0 :(得分:1)
答案 1 :(得分:0)
我能想到的唯一最简单的方法是使用$ GLOBAL
<?php
function my_function($val) {
foreach($GLOBALS as $name => $value) {
if ($value == $val) {
return "Var name: ".$name." , has: ".$val."<br>";
}
}
}
$first = 'John';
$firstname = 'John';
$lastname = 'Doe';
echo my_function($firstname); // outputs: "Var name: firstname , has: John"
echo my_function($lastname);
输出:
Var name: firstname_my , has: John
Var name: lastname_my , has: Doe
假设有2个变量具有相同的
$first = 'John';
$firstname = 'John';
您可以修改代码以区分
function my_function($val) {
foreach($GLOBALS as $name => $value) {
if ($value == $val && substr($name,-3) == "_my") {
return "Var name: ".$name." , has: ".$val."<br>";
}
}
}
$first = 'John';
$firstname_my = 'John';
$lastname_my = 'Doe';
echo my_function($firstname_my); // outputs: "Var name: firstname , has: John"
echo my_function($lastname_my);