Jump to content

function to output multiple variable names, getting the name of a var into a str


JFrankParnell

Recommended Posts

Hi,

 

$mice = array('mickey','minni','mighty');
$pets = array('cow'=>'bessie','dog'=>'fido','mice' => $mice);
$config = 'some setting';

function showvars($message){
$args = func_get_args();
echo"<pre>"; print_r($args);echo"</pre>";
echo "$message <BR>";
foreach ($args as $k=>$v) {
	$name = var_name($k,get_defined_vars());
	echo '$'.$name.' = '.$v."<br>";
}
}

function var_name (&$iVar, &$aDefinedVars){
    foreach ($aDefinedVars as $k=>$v){
        $aDefinedVars_0[$k] = $v;
	}
    $iVarSave = $iVar;
    $iVar     =!$iVar;

    $aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
    $iVar      = $iVarSave;

    return $aDiffKeys[0];

}

echo var_name($mice,get_defined_vars())."<br>";// output: mice  (as expected)

echo showvars('heres the vars:',$pets,$config);

 

the goal here is to have showvars() output something like:

here's the vars:

$pets = array

$config = some setting

 

 

thanks for your time,

J

k, i got this working, please let me know if there is a better way (not having to pass get_defined_vars().  $gdv = get_defined_vars() wouldnt work for me);

 

function dumpvars($message){
$args = func_get_args();
for ($i = 1; $i <= count($args); $i++) {
	foreach ($args[$i] as $k=>$v ){
		$vars[$k] = $v;
	}
}
$out = "/* \n".$message." \n */ \n ";
foreach ($vars as $k=>$v) {
	$out .= ' $'.$k.' = '.var_export($v,true).";\n ";
}
return $out;
}
function var_name (&$iVar, &$aDefinedVars){
    foreach ($aDefinedVars as $k=>$v)
        $aDefinedVars_0[$k] = $v;

    $iVarSave = $iVar;
    $iVar     =!$iVar;

    $aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
    $iVar      = $iVarSave;
return array($aDiffKeys[0]=>$iVar);
}


$mice = array('mickey','minni','mighty');
$pets = array('cow'=>'bessie','dog'=>'fido','mice' => $mice);
$config = 'some setting';

$message= 'heres your vars:';
$out =  dumpvars($message,var_name($pets,get_defined_vars()),var_name($config,get_defined_vars()));

unset($vars,$pets,$config);

echo "<HR><PRE>";	
echo htmlentities($out);
echo "<HR></PRE>";	
  
eval( $out );

echo "<HR><PRE>";	
print_r($pets);
print_r($config);
echo "<HR></PRE>";	

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.