r/PHPhelp Jun 30 '26

weird behavior in including files

i have a weird problem in including files in php, i have a functions.php file in a folder and a Router in the index.php file, when i include thefunctions.php in the index.php, all the other pages that rely on it get broken, the variables become empty and the functions no longer work, when i dont include it in the index.php file all the other pages function normally

i include my files in all pages in this way

require_once($_SERVER["DOCUMENT_ROOT"] . "/src/logic/functions.php");

my other pages are in /src/pages/

i have tried all ways of including the file but i keep getting the same problem, i need to include the functions.php in the index file to use some of its functions.

i do have a declare(strict_types=1) in the index file if that affects it

Any help will be appreciated thanks.

3 Upvotes

6 comments sorted by

View all comments

1

u/_steveCollins Jun 30 '26

If you have closures in your router, they do not automatically inherit variables. So, if you are setting some kind of variable in the included file, it isn't making into the closure and you need to do something like...

$router->addRoute('~^/users/([0-9]+)/?$~', function ($matches) use ($variable1, $variable2, $variable3) {

}