0

I wish to better understand which is the safer way to specify require paths in the following cases. Please, tell me if some is wrong.

main.php
includes
|--afile.php
|--bfile.php
classes
|--aclass.php
|--bclass.php

main.php must include afile.php, so I put in main.php

require_once('includes/afile.php');

afile.php must include aclass.php, so I put in afile.php

require_once('../classes/aclass.php');

aclass.php must include bclass.php, so I put in aclass.php

require_once('bclass.php');

I was wondering if it is correct. I do not mean simply "correct", because I know that it works — I tried — but if this is the best approach. For example, if in future I move a file from a folder to another, I should change all paths in require instruction. If I forget one, I get an error. I was wandering if there is a way to write require so that it always know where is the root.

Looking for best practice.

Thank you in advance.

PS (Follow on EDIT) I found a way that seems to work: that is,

define("ROOT_DIR",__DIR__) 

in my main.php and use ROOT_DIR in all other PHP files. It works even if I move files. There is any reason why I should not use that approach? Suggestions?

  • _"Is that correct?"_ - test it, and you will found out. `require` will throw a fatal E_COMPILE_ERROR level error, when it can't find the file, so you should know pretty immediately. – CBroe Feb 15 '22 at 11:07
  • Yes, of course, but I would like to know NOT ONLY if what I wrote is correct but if it is the best practice or there is a better approach. – Dario de Judicibus Feb 15 '22 at 14:44
  • https://stackoverflow.com/questions/40185747/setting-the-path-for-include-require-files – CBroe Feb 15 '22 at 14:46

1 Answers1

1

Would recommend checking out Magic constants

Example in main.php using DIR (the current directory):

require_once __DIR__.'/includes/afile.php';

Also as you can read here "require_once" and "require" are language constructs and not functions. Therefore they should be written without "()" brackets!

fredriktv
  • 13
  • 6