How can I find out the name of a variable inside a function?

前端 未结 5 913
花落未央
花落未央 2021-01-21 04:46

I have a function

function my_dump($a,$name){
    echo \'
\'.$name.\":\\n\";
    var_export($a);
    echo \'
\'; }

How can

5条回答
  •  深忆病人
    2021-01-21 05:04

    ... I beg your pardon for new answer instead change of previous, but it would be too long (and thus uncomfortable) for reading.

    Below is function from previous answer, that is improved for multiple usage of this function. This version is capable to get name of correct variable in case of multiple usage in one line.

    It is not capable to get name of more than one variable - at least because I don't think it would be good (useful for anything).

    Differences:

    • adding of integer parameter $Index
    • new function for regular expression
    • new regular expression
    • new handling of result of regular expression

    • parameter $Index is not demanded - but its ignoring whenever else than the first usage of that function will give wrong result

    • \x20 in expression means space

    • exception class and exception message in try-catch block may be rewritten as you need

    • protected status of function may be changed or deleted

      protected function Get_VariableNameAsText($Variable="", $Index="")
      {
          $File = file(debug_backtrace()[0]['file']);
      
          try
          {
              if(!empty($Index) && !is_integer($Index))
              {
                  throw new UniT_Exception(UniT_Exception::UNIT_EXCEPTIONS_MAIN_PARAM, UniT_Exception::UNIT_EXCEPTIONS_PARAM_VALTYPE);
              }
          }
          catch(UniT_Exception $Exception)
          {
              $Exception -> ExceptionWarning(__CLASS__, __FUNCTION__, $this -> Get_Parameters(__CLASS__, __FUNCTION__)[1], gettype($Index), 'integer');
          }
      
          for($Line = 1; $Line < count($File); $Line++)
          {
              if($Line == debug_backtrace()[0]['line']-1)
              {
                  preg_match_all('/'.__FUNCTION__.'\((?[a-z]{1,}\:{2}\${1}|\$this\x20{0,1}\-\>{1}\x20{0,1}|\${1})(?[A-Za-z0-9_]{1,})\x20{0,1}\,{0,1}\x20{0,1}(?[0-9]{0,})\x20{0,}\)/', $File[$Line], $VariableName, PREG_SET_ORDER);
      
                  if(empty($Index))
                  {
                      return $VariableName[0]['type'].$VariableName[0]['variable'];
                  }
                  else
                  {
                      return $VariableName[$Index]['type'].$VariableName[$Index]['variable'];
                  }
              }
          }
      }
      

    I hope it will help you, like or better than previous version.

    Edit: New expression allows using of more types of variables (not only common).

提交回复
热议问题