phploopscronredeclare

Problem "cannot redeclare" when the file is included more times - PHP


i'm trying to run the same file more times (again and again...) But i have this problem Cannot redeclare function

This is my code inside the file test.php

$word= hello();
print_r($word);

include('test.php');    


function hello(){
    $x= "ok";
    return $x;
}

When the function print the word i want to run again the same file with include The problem is Cannot redeclare hello()

DETAILS

To run the same file again i could to use a cronjob like to do for other files but in this project i don't know when to run again the file. I must wait the execution of code inside test.php. The execution's time is variable and so i can't to set a cronjob when to run the file every 1 minute or 2 minute.

EDIT: explain more

I have a file called "A.php" where every two minutes two other files are created containing two different arrays (which we will call for simplicity array1.php and array2.php).

Every two minutes a cron job executes "A. php" and the code inside it destroys and creates the two new array files.

In my new project ("test.php") I use the arrays of the two files to send notifications to my telegram. Notifications are sent only and exclusively if there is something new inside these 2 arrays.

If I used a cronjob for "test.php" I could have a problem: if "A.php" for some reason failed to update the two arrays, "test.php" sends the same notifications twice.

For this reason I would like to run "test.php" at the end of the file: at the beginning of test.php extrapolate filemtime () of the two arrays and at the end of "test.php" extract again the filemtime () of the two arrays. If the two files have been updated (they have a different timestamp) I include "test.php" again, otherwise I sleep 10 seconds and repeat the comparison.


Solution

  • Change your cron job so it runs test.php after A.php, but only if A.php is successful.

    */2 * * * * php A.php && php test.php
    

    A.php should exit with a non-zero code if it's not successful; it can do this with

    die(1);
    

    If you want an additional check, test.php can safe the timestamps of the files in another file. When it starts up, it can read that file to get the previous timestamps, and compare the current timestamps with it. If they haven't changed, it doesn't send the notification.