Search code examples
phpfileincluderequire-onceinclude-once

How to solve the fatal error in require_once


My project has two entry point

project (root-folder)
/config(folder)
    config.php
/service(folder)
    service.php
index.php

for example

File 1:/index.php ( first entry point) - here we include the config form the config folder

<?php
require_once('config/config.php');
require_once('service/service.php');
?>

File 2:service/service.php - here we include the config form the config folde

<?php
require_once('../config/config.php');

?>

if i call the File 2:service/service.php has no fatal error

but when i call the File 1:/index.php it became the fatal error as failed to require 'service/service.php' because it require again and config path is invalid

How to solve this issue.


Solution

  • Reason:

    This issue arises because your execution starts from index.php and then you require service/service.php. Now in service.php when you do ../config/config.php, PHP tries to resolve the directory path from index.php point of view and it doesn't find any such file or directory. Hence, the error.

    Solution:

    Declare a constant in index.php. Check if this constant exists in service/service.php. If not, then require it, else skip it like below:

    index.php:

    <?php
       define('INDEX_ENTRY_POINT',true);
       require_once('config/config.php');
       require_once('service/service.php');
    ?>
    

    service.php:

    <?php
       if(!defined('INDEX_ENTRY_POINT')){
         require_once('../config/config.php');
       }
    ?>
    

    Note: It is always better to use __DIR__ giving absolute paths than relative paths to avoid such issues.