I am doing some PHP programming and have a question: How can I load a PHP function when the PHP script is first run, and only when it is first run?
thanks
You can use a Lock file
$lock = "run.lock" ;
if(!is_file($lock))
{
runOneTimeFuntion(); //
touch($lock);
}
Edit 1
One Time Function
runOneTimeFuntion ();
runOneTimeFuntion ();
runOneTimeFuntion ();
runOneTimeFuntion ();
runOneTimeFuntion ();
runOneTimeFuntion ();
runOneTimeFuntion ();
runOneTimeFuntion ();
function runOneTimeFuntion() {
if (counter () < 1) {
var_dump ( "test" );
}
}
function counter() {
static $count = 0;
return $count ++;
}
Output
string 'test' (length=4)
EACH time you start a PHP script, it starts as a new one, no matter how much times it was called before.
And if you are aware of re-declaration of functions, which is forbidden in PHP, load functions from external files using:
<?php require_once("my_function_file.php"); ?>
If you want a script to remember if it was called before, it's possible to do using some form of logging (data base\file) and checking it before load... But I don't see any reason for this in case of function load...
There is a PHP function called function_exists
You can define your own function within this function, and then you could see whether this exists or not.
if (!function_exists('myfunction')) {
function myfunction() {
// do something in the function
}
// call my function or do anything else that you like, from here on the function exists and thus this code will only run once.
}
Read more about function_exists here: http://www.php.net/function_exists