Dario de Judicibus
Dario de Judicibus

Reputation: 161

Correct relative paths for require_once()

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?

Upvotes: 0

Views: 358

Answers (1)

fredriktv
fredriktv

Reputation: 13

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!

Upvotes: 1

Related Questions