테스트 사이트 - 개발 중인 베타 버전입니다

넘겨온 변수의 이름을 추출하는 함수..

· 16년 전 · 1365 · 1

값이아니라 변수명입니다~

 Here s a function to get the name of a given variable.  Explanation and examples below.

   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;
   }


 Explanation:

 The problem with figuring out what value is what key in that variables scope is that several variables might have the same value.  To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match.  Then we loop through the scope the variable is contained in and when there is a match of our modified value, we can grab the correct key.

 Examples:

 1.  Use of a variable contained in the global scope (default):
 < ?php
   $my_global_variable = "My global string.";
   echo vname($my_global_variable); // Outputs:  my_global_variable
 ? >

 2.  Use of a local variable:
 < ?php
   function my_local_func()
   {
     $my_local_variable = "My local string.";
     return vname($my_local_variable, get_defined_vars());
   }
   echo my_local_func(); // Outputs: my_local_variable
 ? >

 3.  Use of an object property:
 < ?php
   class myclass
   {
     public function __constructor()
     {
       $this->my_object_property = "My object property  string.";
     }
   }
   $obj = new myclass;
   echo vname($obj->my_object_property, $obj); // Outputs: my_object_property
 ? >
 =>2줄로
 < ?php
 function var_name(&$var, $scope=0)
 {
     $old = $var;
     if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;
 }
 ? >

[이 게시물은 관리자님에 의해 2011-10-31 17:16:08 PHP & HTML에서 이동 됨]

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

댓글 1개

찾다찾다 여기서 찾게 되었네요. 정말 감사합니다.
그러고보니 딱 일년전 글이군요 ㅎ

게시글 목록

번호 제목
8050
8048
19969
19968
19967
19966
19965
19964
19963
19962
19961
28345
31017
19960
19959
19958
19957
8039
8035
8029
28344
28339
8019
28338
8017
8010
8007
8004
8003
28332
28322
7999
28317
20956
7992
20945
28314
20936
20931
7986
20925
7982
7979
7978
7975
28307
7973
7966
28305
7963
28300
7961
28297
28295
7959
19948
19947
28292
31016
19946
19945
28286
7958
7956
7952
7946
28285
28283
19943
7944
7936
7931
28279
24666
24663
7928
7923
19941
28274
28257
28249
28248
7914
7912
7911
20912
7908
31755
28233
28232
28228
7903
28217
20900
24662
20891
20882
19936
20853
31011