获取字符串中变量的名称

时间:2015-03-28 10:02:41

标签: php function variables

您好我想创建一个函数,我可以在其中传递变量并输出变量的名称及其值作为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"

2 个答案:

答案 0 :(得分:1)

查看get_defined_vars()

你可以var_dump这个,它会显示你定义的所有变量。然后你可以遍历并转储每个值。

http://php.net/get_defined_vars

答案 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);