简体   繁体   中英

Require Once Failing Relative Path

I have the following file structure in my project:

+ server
  + api
    + product
      - get.php
  + database
    - product.php
  + model
    - product.php
  + service
    - product.php
  + utilities
    - controller.php
    - database.php

Then in my server/api/product/get.php I have the following lines:

require_once("../../service/product.php");
require_once("../../utilities/controller.php");

I believe this is properly loading the service because when I use Insomnia to hit the endpoint I am getting this error in the server/api/service/product.php file:

Warning: require_once(../model/product.php): failed to open stream: No such file or directory in C:\full path removed\server\service\product.php on line 2

Fatal error: require_once(): Failed opening required '../model/product.php' (include_path='C:\xampp\php\PEAR')

In my server/service/product.php file I have the following:

require_once("../model/product.php");
require_once("../database/product.php");

And it is failing on the first require_once .

So my question to y'all is why would the relative path in my controller layer work, but the relative path in the service layer fail?

You could as an alternative use the __DIR__magic constant as per the documentation the constant gives: 'The directory of the file. If used inside an include, the directory of the included file is returned'. Which reduces the likelihood of errors through relative pathing.

Example:

require_once(__DIR__ . "/../../service/product.php");

Use include and require never without __DIR__. A relative path that starts with. or.. has the current directory as a base. The current working directory depends on various settings. __DIR__ is always the directory where the file itself is located.

For include the server/service/product.php from the file server/api/product/get.php you can do this:

require_once __DIR__."/../../service/product.php";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM