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 php script he starts as a new one, no matter how much times it was called befor.
And if you aware of re-declare functions, which is forbided in PHP, load functions from external fles useing:
<?php require_once(my_function_file.php); ?>
If you want scrpt remember if he was called befor, it's possible to do using some form of logging (data base\file) and cheacking it befor load... But I don't see any reason for this in case of function load...
Or use a plain boolean...
$bFirstRun = true;
if( $bFirstRun ) {
run_me();
$bFirstRun = false;
}
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