note 103519 added to function.get-defined-vars

From: Date: Mon, 18 Apr 2011 12:32:18 +0000
Subject: note 103519 added to function.get-defined-vars
Groups: php.notes 
Request: Send a blank email to php-notes+get-178935@lists.php.net to get a copy of this message
get_defined_vars() returns ALL the vars (in the current scope), what if you just want all YOUR vars, not PHP's super-globals? Well, I tinkered with code for hours until I got this 1-liner that "does what I want", but I don't know why it "works" (& I don't wanna {can't} ask "why does it work?", cuz then you'd delete my note {sheesh!}). <?php var_export(array_diff(get_defined_vars(), array(array()))); ?> Example... <?php $TOP_LEVEL_VAR=1; var_export(array_diff(get_defined_vars(), array(array()))); ?> The output (with register_globals off) should be... array ( 'TOP_LEVEL_VAR' => 1, ) ...it perfectly eliminated all the super-globals, without me having to specify them! (note with register_globals on, the output includes those globals, then TOP_LEVEL_VAR). Here it is, as a function...(it's the best I could do {I can't call get_defined_vars() inside get_user_defined_vars() cuz of the scope issue}). <?php header('Content-type: text/plain'); $TOP_LEVEL_VAR=1; echo 'register_globals('; echo ini_get('register_globals'); echo ') '.phpversion()."\n"; var_export(get_user_defined_vars(get_defined_vars())); function get_user_defined_vars($vars) { return array_diff($vars, array(array())); } ?> Note that originally I had an array of the super-globals I wanted removed from get_defined_vars()'s array, then I noticed even an empty double-array, array(array()), made it give me the correct result. Weird. This was tested on PHP 5.2.9. NOTE: I should *NOT* need to answer the SPAM challenge on every *preview*! ---- Server IP: 69.147.83.197 Probable Submitter: 68.58.143.183 ---- Manual Page -- http://www.php.net/manual/en/function.get-defined-vars.php Edit -- https://master.php.net/note/edit/103519 Del: integrated -- https://master.php.net/note/delete/103519/integrated Del: useless -- https://master.php.net/note/delete/103519/useless Del: bad code -- https://master.php.net/note/delete/103519/bad+code Del: spam -- https://master.php.net/note/delete/103519/spam Del: non-english -- https://master.php.net/note/delete/103519/non-english Del: in docs -- https://master.php.net/note/delete/103519/in+docs Del: other reasons-- https://master.php.net/note/delete/103519 Reject -- https://master.php.net/note/reject/103519 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#178935) next »