How to solve the fatal error in require_once

1.2k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

You have to consider that when you call service.php from index.php, the root is that of index.php. Now there are many ways to get around this. You could decide that service.php is a main controller, just as is index.php, and thus belongs in the root folder. If for some reason you want to keep it as it is, then you have to define the root in order for it to adapt to the situation as in vivek_23 answer just above. Personally, i would keep service.php in the root folder, it is more logic.