I’m new to OOP terminology, I am trying to create a class that make a hit counter.
I try the code below but it create just a counter.txt page with inside value 1. I dont know why its not incrementing.
class LOGFILE {
public function READ($FileName) {
$handle = fopen($FileName, 'r');
$fread = file_get_contents($FileName);
return $fread;
fclose($handle);
}
public function WRITE($FileName, $FileData) {
$handle = fopen($FileName, 'w');
$FileData = $fread +1;
fwrite($handle, $FileData);
fclose($handle);
}
}
$logfile = new LOGFILE();
$logfile -> WRITE("counter.txt",$FileData);
echo $logfile -> READ("counter.txt");
The reason is that
$freadis local variable for bothREADandWRITEmethods. You need to make itprivateglobal variable for your class:Note: I have removed
fopenandfclosebecausefile_get_contentsdoes not need it. In write you can usefile_put_contents. Removed not used variable$FileDatatoo. It’s always a good practice to create variables methods and classes when they are needed.Also take a look at best practices how to name your classes, variables, methods and so on. Here’s best guide, IMO.