简体   繁体   English

在PHP中,如何将参数名称转换为字符串

[英]In PHP, How to Convert an Argument Name into a String

My goal is to echo the argument passed to a function. 我的目标是回显传递给函数的参数。 For example, how can this be done? 例如,如何做到这一点?

$contact_name = 'foo';

function do_something($some_argument){
// echo 'contact_name'  .... How???
}

do_something($contact_name);

You can't. 你不能 If you want to do that, you need to pass the names as well, eg: 如果要这样做,还需要传递名称,例如:

$contact_name = 'foo';
$contact_phone = '555-1234';

function do_something($args = array()) {
    foreach ($args as $name => $value) {
        echo "$name: $value<br />";
    }
}

do_something(compact('contact_name', 'contact_phone'));

To track Variable name You can throw and catch Exception. 跟踪变量名称您可以引发并捕获Exception。 In penultimate line of trace is information about this function name and name of variables. 倒数第二行是有关此函数名称和变量名称的信息。

Example how use this: http://blog.heintze.pl/2012/01/12/lepszy-var_dump-czyli-przyjemniejsze-debugowanie-php/ to create better var dump (Link to code: http://blog.heintze.pl/wp-content/uploads/2012/01/bigWeb.zip ) 例如如何使用: http://blog.heintze.pl/2012/01/12/lepszy-var_dump-czyli-przyjemniejsze-debugowanie-php/创造更好的变种转储(链接代码: HTTP://blog.heintze .pl / wp-content / uploads / 2012/01 / bigWeb.zip

Unfortunately - this article is only in polish at this time. 不幸的是-这篇文章目前只有波兰语。

Straight off the PHP.net variables page: 直接访问PHP.net 变量页面:

<?php
  function vname(&$var, $scope=false, $prefix='unique', $suffix='value')
  {
    if($scope) $vals = $scope;
    else $vals = $GLOBALS;
    $old = $var;
    $var = $new = $prefix.rand().$suffix;
    $vname = FALSE;
    foreach($vals as $key => $val) {
      if($val === $new) $vname = $key;
    }
    $var = $old;
    return $vname;
  }
?>

不可能。

Variables are just means to address values or areas in the memory. 变量只是解决内存中的值或区域的手段。 You cannot get the variable name that's value has been passed to a function. 您无法获取已将值传递给函数的变量名称。

Disclaimer: this will oonly work if you pass a variable to the function, not a value, and it only works when your not in a function or a class. 免责声明:如果您将变量而不是值传递给函数,这将非常有用,并且仅当您不在函数或类中时才起作用。 So only the GLOBAL scope works :) 因此,只有GLOBAL范围有效:)

Good funct($var)
Bad funct(1)

You can do it actually contrary to popular believe ^_^. 您实际上可以做到这一点,与流行的看法^ _ ^相反。 but it involves a few lookup tricks with the $GLOBALS variable. 但是它涉及到$ GLOBALS变量的一些查找技巧。

you do it like so: 你这样做是这样的:

$variable_name = "some value, better if its unique";

function funct($var) {
   foreach ($GLOBALS as $name => $value) {
      if ($value == $var) {
         echo $name; // will echo variable_name
         break;
      }
   }
}

this method is not fool proof tho. 这种方法不是万无一失的。 Because if two variables have the same value, the function will get the name of the first one it finds. 因为如果两个变量具有相同的值,则该函数将获得它找到的第一个变量的名称。 Not the one you want :P Its best to make the variable value unique before hand if you want accuracy on variable names 不是您想要的变量:P如果希望变量名称的准确性,最好事先使变量值唯一

Another method would be to use reference to be accurate like so 另一种方法是像这样使用引用准确

$variable_name = 123;

function funct(&$var) {

   $old = $var;
   $var = $checksum = md5(time());  // give it unique value

   foreach ($GLOBALS as $name => $value) {
      if ($value == $var) {
         echo $name; // will echo variable_name
         $var = $old; // reassign old value
         break;
      }
   }
}

so it is entirely possible :) 所以这完全有可能:)

Based on PTBNL's (most definately correct) answer i came up with a more readable (at least i think so) approach: 基于PTBNL的(最肯定是正确的)答案,我想出了一种更具可读性(至少我认为是这样)的方法:

/**
 * returns the name of the variable posted as the first parameter.
 * If not called from global scope, pass in get_defined_vars() as the second parameter
 *
 * behind the scenes:
 *
 *   this function only works because we are passing the first argument by reference.
 *   1. we store the old value in a known variable
 *   2. we overwrite the argument with a known randomized hash value
 *   3. we loop through the scope's symbol table until we find the known value
 *   4. we restore the arguments original value and
 *   5. we return the name of the symbol we found in the table
 */
function variable_name( & $var, array $scope = null )
{
    if ( $scope == null )
    {
        $scope = $GLOBALS;
    }

    $__variable_name_original_value = $var;
    $__variable_name_temporary_value = md5( number_format( microtime( true ), 10, '', '' ).rand() );
    $var = $__variable_name_temporary_value;

    foreach( $scope as $variable => $value )
    {
        if ( $value == $__variable_name_temporary_value && $variable != '__variable_name_original_value' )
        {
            $var = $__variable_name_original_value;
            return $variable;
        }
    }
    return null;
}

// prove that it works:

$test = 1;
$hello = 1;
$world = 2;
$foo = 100;
$bar = 10;
$awesome = 1;

function test_from_local_scope()
{
    $local_test = 1;
    $local_hello = 1;
    $local_world = 2;
    $local_foo = 100;
    $local_bar = 10;
    $local_awesome = 1;

    return variable_name( $local_awesome, get_defined_vars() );
}
printf( "%s\n", variable_name( $awesome, get_defined_vars() ) ); // will echo 'awesome'
printf( "%s\n", test_from_local_scope() ); // will also echo awesome;

Sander has the right answer, but here is the exact thing I was looking for: 桑德(Sander)的答案正确,但这正是我一直在寻找的东西:

$contact_name = 'foo';

function do_something($args = array(), $another_arg) {
    foreach ($args as $name => $value) {
        echo $name;
        echo '<br>'.$another_arg;
    }
}

do_something(compact(contact_name),'bar');
class Someone{
  protected $name='';
  public function __construct($name){
    $this->name=$name;
  }

  public function doSomthing($arg){
     echo "My name is: {$this->name} and I do {$arg}";
  }
}

//in main
$Me=new Someone('Itay Moav');
$Me->doSomething('test');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM