0

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

4 Answers 4

4

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)
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you Baba. That works well. However, if i close the browser and then load the same page, it doesnt detect it as a first page load. Do I have to maybe unlock the lock when the user has done with the page?
You can not really, see the many duplicates that cover that like stackoverflow.com/questions/2195581/…
never knew you want it to reload after you close the browser .. i would update my code in min
I am not really sure how that code is meant to work... isn't there just a simple way to unlock the lock... the lock statment is otherwise working very well.
Use said you want a function to run once ...that mean it must not be called anywhere in php ...... by mistake or on purpose .. is that not what you want ???
|
1

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

Comments

0

Or use a plain boolean...

$bFirstRun = true;

if( $bFirstRun ) {
    run_me();
    $bFirstRun = false;
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.