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

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

· 16년 전 · 1367 · 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개

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

게시글 목록

번호 제목
13454
29442
13451
13448
13446
13445
13442
13439
13437
13434
13429
13425
13423
13418
13410
13408
13407
13406
29441
13405
13404
13401
13400
13399
13395
13391
29435
13389
13386
13381
13377
13370
13367
13366
13364
13362
29432
29428
13361
13360
13358
13354
13351
29427
13346
13340
13337
13334
13328
13326
13325
13324
13323
29426
13322
13321
13315
29424
13312
29422
25114
13308
13307
13305
13304
25111
29421
13301
13299
13296
13292
13291
13290
13289
13288
13287
13286
13285
13284
29420
13283
13277
13274
13266
13265
13262
13261
13259
13254
13250
29419
13242
13241
13236
13235
29418
29417
13234
13233
13231