Search code examples
phpclassfwriteinstances

PHP - Instantiated class function calling twice


I'm trying to guess why an undesired action is performing in my code. This is my code:

index.php

include_once("MyClass.php");
new MyClass();

MyClass.php

class MyClass{

     private $LOG;

     function __construct(){

        require_once("Initializer.php");
        $initializer = new Initializer();
        $this->LOG = $initializer->log;

        //Calling the function that performs twice
        $this->LOG->log("test");

     }

}

Initializer.php

class Initializer{

     public $log;

     function __construct(){

          require_once("Log.php");
          $this->log = new Log();

     }

}

Log.php

class Log{

     function __construct(){
           echo "This is not displaying twice";
     }

     //This function is performing twice
     public function log($msg){
        $logFile = fopen(TARGET_FILE, "a+");
        fwrite($logFile, $msg . "\n");
        fclose($logFile);
     } 

}

I'm getting as an output in TARGET_FILE:

test
test

Everytime I execute index.php.

Where's the problem? Thanks in advance.


Solution

  • It had nothing to do with PHP. I checked my .htaccess file which had this rules:

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^(.+) index.php [L]
    

    I removed RewriteCond %{REQUEST_FILENAME} !-d and it works as expected.