php - Is it possible to get variables with get_defined_vars() but for the actual running script? -


i'm trying create function user-defined variables for, selectively, unsetting them before script finishes. in order used variables, must use get_defined_vars() function php provides with, has caveat (for me, @ least...): works in scope it's called.

i to, ideally, encapsulate in function inside framework core namespace, \helpers\core function \helpers\core\getvariables().

actually, code looks this:

foreach (array_diff(array_keys(get_defined_vars()), ["_cookie", "_env", "_files", "_get", "_post", "_request", "_server", "_session", "argc", "argv", "globals", "http_raw_post_data", "http_response_header", "ignore", "php_errormsg"], ["page"]) $variable) {     unset($$variable); } 

basically, tries automate variable selection by:

  • getting variable names array_keys(get_defined_vars())
  • defining set of reserved or system-wide variables $_get, $_post, $_server , on
  • providing of used variables preserved (in example, $page)

the problem not place code every place want rid of variables at. ideally, able define function , automate use, but... there way accomplish in current script call function from?

you can use $globals instead of get_defined_vars() access global scope , unset global variables:

$non_user_vars = ["_cookie", "_env", "_files", "_get", "_post", "_request",                    "_server", "_session", "argc", "argv", "globals",                   "http_raw_post_data", "http_response_header",                   "ignore", "php_errormsg"];  $safe_user_vars = ["page"];  $all_vars = array_keys($globals);  $user_vars = array_diff($all_vars, $non_user_vars, $safe_user_vars);  foreach($user_vars $variable) {     unset($globals[$variable]); } 

quick caveats approach:

  1. to make cleaner, defined arrays first. result in them getting $user_vars array (thought shouldn't if not global) defend against avoid throwing error or other consequences.

  2. your array of non-user variables not exhaustive, when tested above, still got:

    array (     [2] => http_env_vars     [6] => http_post_vars     [8] => http_get_vars     [10] => http_cookie_vars     [12] => http_server_vars     [14] => http_post_files     [16] => test     [17] => non_user_vars ) 

if don't want guess pre-defined or visible @ runtime, maybe there initial call \helpers\core\getvariables() gets list of variables , stores them statically array_diff needs diff initial list list @ end know user-defined.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -