K
K
Kirill Gorelov2015-10-31 15:38:37
PHP
Kirill Gorelov, 2015-10-31 15:38:37

Functions in php?

Hello.
With etude programming. Faced such a problem.
Made a simple function to write to a file.

function writtetwoLog(){ 
$entry_line = "$dtime - Сайт все еще не доступен \n";
$fp = fopen("logs.txt", "a");
fputs($fp, $entry_line);
fclose($fp);
}

The $dtime variable contains the time. But it doesn't work if the script that determines the time is outside the function that writes to the file. And nothing is displayed for this.
Is this somehow solved, besides what would the time script be written to the file writing function ??

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Max Payne, 2015-10-31
@YardalGedal

function writtetwoLog($dtime){ 
    $entry_line = "$dtime - Сайт все еще не доступен \n";
    $fp = fopen("logs.txt", "a");
    fputs($fp, $entry_line);
    fclose($fp);
}

writtetwoLog($dtime);

or this option (but I highly do not recommend)
// $dtime = ...
function writtetwoLog(){ 
    global $dtime; 
    $entry_line = "$dtime - Сайт все еще не доступен \n";
    $fp = fopen("logs.txt", "a");
    fputs($fp, $entry_line);
    fclose($fp);
}

S
Sergey, 2015-10-31
Protko @Fesor

1) all variables must be passed into the function explicitly. Avoid using global variables.
2) if $dtimeit is the logging function that is needed (it is part of the log format), and this is the current time (usually we need to remember when we wrote it to the log), then we can simply get the current time inside the function.
3) if $dtimethis is not the current time, but just some kind of variable, add it to the message and pass it inside:

function log($message) {
   // ...
}

log("$dtime - Сайт все еще не доступен");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question