Page 1 of 1

Understanding Functions and Includes

Posted: Thu Jan 05, 2006 12:23 pm
by dwessell
Hi all.

I have a file called 15min.php and one called mailer.php.. They both reside in the same directory.

In the file 15min.php, I have an include statement.

Code: Select all

include 'mailer.php';
Further down inside the 15min.php file.. I have a while loop:

Code: Select all

while( $rowOne = mysql_fetch_array($resultThree, MYSQL_NUM) ){
sendSMS($rowOne[1],$resultTwo);	
}
Now.. $rowOne should be coming back as null, as there's nothing in the database (Queries are made further up in the code).. So sendSMS should not be called.

sendSMS() is a function inside of mailer.php... And down in mailer.php is an echo line to let me know that the code has been run..

When I run 15min.php, I see the echo from mailer.php, even though the only line from mailer.php (sendSMS())shouldn't be called as it's in a while loop that I'm pretty sure isn't exectuing.

Scratch that.. I just put an echo in that while loop, and it's not running..

So... Would someone help me understand why the echo from mailer.php would be running, even though none of the code is used? Is this a byproduct of 'include'?

Thanks
David

Posted: Thu Jan 05, 2006 12:50 pm
by feyd
including a file runs it.. any code that isn't inside a function is run at the time of inclusion.

Posted: Thu Jan 05, 2006 12:56 pm
by dwessell
feyd,

Thanks for the response.. I guess that's the only logical conclusion from the results.. But was was running so counter intuitive to what I thought would happen, that I was looking for other alternatives.

So.. If I only want that code to run, when called.. What would be a solution? Putting the code in the same file, in a function further down?

If I have

Code: Select all

<?php

function call

?>

<?php

function(){

}

?>
Will I be able to call the function from the first block?

Thanks for any suggestions..

Oh while I'm asking questions.. PHP has function calls made by value by default.. Correct? By reference calls are made with the standard '&'?

Thanks
David

Posted: Thu Jan 05, 2006 1:14 pm
by feyd
dwessell wrote:So.. If I only want that code to run, when called.. What would be a solution? Putting the code in the same file, in a function further down?
The code must be contained in a function and the function must not be called except where expressly needed.
dwessell wrote:Will I be able to call the function from the first block?
Try it out. ;)
dwessell wrote:Oh while I'm asking questions.. PHP has function calls made by value by default.. Correct? By reference calls are made with the standard '&'?
yes, & is used to do by-reference passes, however you need to make sure your settings allow passing by reference or you will get warning/notices about it.