Jump to content

Pass variables between functions


snorky

Recommended Posts

I have a script that consists of

  • Some variables declared in the body of the script. They will become global variables used throughout the script.
  • 5 functions:

  1. function openFileIn() - opens a text file for reading
  2. function openFileOut() - creates and opens a log file (text) for writing
  3. function loop0() - is a loop that uses global variables  AND calls the next two functions(see below)
  4. function getValues() - reads one line from the input file and processes it to create variables specific to the current iteration of the loop
  5. function lookUps() - executes commands using the global variables AND (hopefully) variables created in function getValues(), writes the results to the log file, and hands control back to the while statement.

 

All of the variables declared in the body of the script easily pass to functions by identifying them as global when using them in a function.


The problem: how do I pass the values of the variables in function getValues() to function lookUps() ? Using the global declaration doesn't work.


Note: the "echo" commands in functions loop0(), getValues(), and lookUps() are there for debugging. The results of the echo commands tell me where things are working correctly - or not.

 

The script:



<?php  /* -- compare nslookup for hostname & ip address -- */

// -----begin vars -----------

        $dir = ".";                     // folder for input and results files
        $thisDay = date("Ymd");                    //  date used in file names ex: 20100316

        $fileIn = $thisDay . "-panda.txt";     //  input file
        $fileOut = $thisDay . "-results.txt"; //  results file

        $handleIn = fopen($fileIn,  'r');        //  open input file read-only

        $textA = " - computers without Panda\n";  //  part of header line in results page
        $textB      = $thisDay.$textA;

// -----end vars ------------

// ----- begin functions -------------

      function finis()              // the last step in the script
        {
          global $fileIn;
          global $fileOut;
          close ($fileIn);
          close ($fileOut);
          exit();
        }

      function openFileOut()        // create log file
      {
        global $fileOut;
        global $textB;
        fopen($fileOut, 'w');                          //  open the output file for write
        fwrite($fileOut, $textB);                      //  print header line at top of results page
      }                                                //  leave results page open for more writes

      function openFileIn()        // open input file (text)
      {
        global $fileIn;
        fopen($fileIn,'r');                            //  open the input file for read
      }

  /* --- example of values in function getValues()

    $data = OHE-CL30,10.11.1.59
  $z = 19                      //  count of chars in entire line
  $b = 8                      //  location of comma
    $a = 0,7    "OHE-CL30"      //  1st substring in $data
  $c = 9,18    "10.11.1.59"    //  2nd substring in $data

  --- end example -------------- */

      function getValues()
      {
        global $handleIn;
        $data=fgets($handleIn);            //  the string being read
        // example: OHE-CL30,10.11.1.59    //  each line of input file resembles this:
                                            //  hostname,ip address

        $z = strlen($data);                //  how many chars in entire line
        // example: 19

        $b = strpos($data,",");            //  find the comma
        // example: 8

        $a = substr($data,0,($b-1));     //  hostname
        // example: 0,7    "OHE-CL30"

        $c = substr($data,($b+1),($z - 1)); //  ip address
        // example: 9,18    "10.11.1.59"

//      used for debugging; it shows that this function works as expected
//        $m = ", ";
//        echo $data . $z . $m . $b . $m . $a . $m . $c . "\n";

      }

      function lookUps() // compare and reverse compare IPs & HOSTNAMES
      {
        global $a;
        global $c;
        global $fileOut;
//        echo "a = " . $a . ", c = " . $c . ", logfile = " . $fileOut . "\n";    //  for debugging
        $aa = "nslookup" . $a . " >> " . $fileOut;
        $cc = "nslookup" . $c . " >> " . $fileOut;
        shell_exec($aa);
        shell_exec($cc);
//        exec($aa);
//        exec($aa);
//        passthru($aa);
//        passthru($cc);

      }

      function loop0()
      {
        global $handleIn;
        $counter=1;
        while (!feof($handleIn))
        {
          getValues();
//          echo $counter . "\n"; // testing for progress of the loop
          $counter++;
          lookUps();
        }
      }

// ----- end functions -------------

/* ------------ runtime ------------ */

openFileIn();
openFileOut();
loop0();
echo " ======== closing files and going home =========\n";
finis();

?>

Link to comment
Share on other sites

"Functions can both accept and return values. Its a simple concept."

 

The problem: how do I pass the values of the variables in function getValues() to function lookUps()  ? Using the global declaration doesn't work.

Link to comment
Share on other sites

"Functions can both accept and return values. Its a simple concept."

 

The problem: how do I pass the values of the variables in function getValues() to function lookUps()  ? Using the global declaration doesn't work.

 

$values = getValues();
lookUps($values);

Link to comment
Share on other sites

That makes sense. Thanks.

 

However.... the script still does not return what I expect. If I throw in some debugging code, I can see that "everything" would work correctly if the values of $a and $c (in the complete script at the bottom) are passed from getValues() to lookUps().

 

[ pseudo code ] :

 

getValues()	

$a = [statementX] $inputFile;	
return $a;

lookUps()

global $a;
$aa = "nslookup" . $a;			
exec($aa);				//	This is not the problem. 
						//	The problem is that there is nothing to execute (see below).

loop0()
global $a;

while(!feof($inputFile))	// repeats lookUps() until feof($inputFile)
{
	$values = getValues();
	lookUps($values);
}

 

lookUps() should process $a to create $aa - an argument for an execute statement: exec(), shell_exec(), passthru(), etc. However, no value for $a is passed to this function. I can tell there is no value by testing for $a before the $aa assignment.

 

Using or not using the global and return statements makes no difference. $a is not passed from getValues() to lookUps().

 

The early parts of the script (see below) work well. In other words, the values for $a and $c are created correctly.

 

I don't like to ask so many questions, but after several hours of research and testing I'm still hitting the wall. I really appreciate the help of people far more skilled than I.

 

The complete script is:

								
<?php   // -- run nslookup for hostname & ip address and compare results -- */

// -----begin vars -----------
$dir = ".";                                 //	folder for input and results files
$thisDay = date("Ymd");                     //  date used in file names ex: 20100316
$fileIn = $thisDay . "-panda.txt";          //  input file
$fileOut = $thisDay . "-results.txt";       //  results file
$handleIn = fopen($fileIn,'r');             //  open input file read-only
$textA = " - computers without Panda\n";    //  part of header line in results page
$textB = $thisDay . $textA;
// -----end vars ------------

// ----- begin functions -------------

function finis()                            // the last step in the script
{
	global $fileIn;
	global $fileOut;
	close($fileIn);
	close($fileOut);
	exit ();
}

function openFileOut()                      // create log file
{
	global $fileOut;
	global $textB;
	fopen($fileOut,'w');                    //  open the output file for write
	fwrite($fileOut,$textB);                //  print header line at top of results page
                                        		//  leave results page open for more writes
}

function openFileIn()                       // open input file (text)
{
	global $fileIn;
	fopen($fileIn,'r');                     //  open the input file for read
}
    	/* --- example of values in function getValues()

    	$data	=	OHE-CL30,10.11.1.59
    	$z		=	19                      //  count of chars in entire line
    	$b		=	8                       //  location of comma
    	$a		=	0,7     "OHE-CL30"      //  1st substring in $data
    	$c		=	9,18    "10.11.1.59"    //  2nd substring in $data

    	--- end example -------------- */

function getValues()
{

	global $handleIn;
	global $thisDay;
	global $fileIn;
	global $fileOut;
	global $textA;
	global $textB;

	$data = fgets($handleIn);               //  the string being read
    		//  example: OHE-CL30,10.11.1.59
    		//  each line of input file resembles this : hostname,ip address   */
	$z = strlen($data);                     //  how many chars in entire line
    		//    example: 19
	$b = strpos($data,",");                 //  find the comma
    		//    example: 8
	$a = substr($data,0,($b - 1));          //  hostname
    		//    example: 0,7     "OHE-CL30"
	$c = substr($data,($b + 1),($z - 1));   //  ip address
    		//   example: 9,18    "10.11.1.59"

        return $a;
        return $c;
}

function lookUps()		//	compare and reverse compare IPs & HOSTNAMES
{
	global $a;
	global $c;

	$aa = "nslookup" . $a;
	$cc = "nslookup" . $c;

        // then use shell_exec() or exec() or passthru()

}

function loop0()
{
	global $handleIn;
	global $a;
	global $c;
	$counter = 1;       //  initialize counter @1
	while(!feof($handleIn))
	{
		$values = getValues();
		lookUps($values);
	}
}

// ----- end functions -------------

/* ------------ runtime ------------ */

openFileIn();
openFileOut();
loop0();
echo " ======== closing files and going home =========\n";
finis();
?>

Link to comment
Share on other sites

globals are bad for all sorts of reason, don't use them.

 

When I was learning C and Pascal (80s, early 90s), someone showed me these cool tricks involving globals. They did the job back then (MS-DOS). I don't write a lot of code, so I haven't screwed up enough to learn how to break those old bad habits. I'm trying to learn better ways - hence my questions.

 

Functions can both accept and return values. Its a simple concept.

Link to comment
Share on other sites

When I was learning C and Pascal (80s, early 90s), someone showed me these cool tricks involving globals. They did the job back then (MS-DOS). I don't write a lot of code, so I haven't screwed up enough to learn how to break those old bad habits. I'm trying to learn better ways - hence my questions.

 

So stop using them and start passing arguments into functions and returning output from functions.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.