[英]Get the name of a variable in a string
Hi I want to create a function in which I can pass a variable and output the name of the variable and its value as a sting. 嗨,我想创建一个函数,在该函数中我可以传递变量,并以字符串形式输出变量的名称及其值。 Something like this:
像这样:
$firstname = 'John';
$lastname = 'Doe';
echo my_function($firstname); // outputs: "Var name: firstname , has: John"
echo my_function($lastname); // outputs: "Var name: lastname , has: Doe"
Take a look at get_defined_vars()
看看
get_defined_vars()
You can var_dump this and it will show all the variables you defined. 您可以var_dump这,它将显示您定义的所有变量。 You could then loop through and dump each ones value too.
然后,您可以遍历并转储每个值。
http://php.net/get_defined_vars http://php.net/get_defined_vars
The only easiest way i can think of this time is make use of $GLOBAL 我这次能想到的最简单的方法就是利用$ 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);
Output: 输出:
Var name: firstname_my , has: John
Var name: lastname_my , has: Doe
Let say if there is 2 variables with same 假设是否有两个相同的变量
$first = 'John';
$firstname = 'John';
You can modify your code to differentiate like this 您可以修改代码以像这样区分
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.