Include_once and directional directories - php

0

I'm having problems with include in relation to directories, because when I call a class from another directory that contains another include the paths are different. I need to know if there is any way to unify these includes and always call them the same way, does anyone have any ideas?

    
asked by anonymous 06.01.2015 / 21:21

2 answers

1

If you do not use namespaces , the best way to do this is to always take into account the absolute path of system files, not relative paths - that is, the path of a file relative to other.

In addition, always use the following magic constants to make it easier to include files:

  • __FILE__ (to reference the current file), and
  • __DIR__ (to reference the current file directory).

For example:

index.php:

<?php
require_once(__DIR__ . '/bootstrap.php');

bootstrap.php:

<?php
require_once(__DIR__ . '/autoload.php');
require_once(__DIR__ . '/config/config.php');
require_once(__DIR__ . '/app/url_router.php');

Now, if you use version 5.3 of PHP or higher, suddenly it's worth thinking about namespaces. So, instead of including the files manually, the organization of the classes takes into account the directory structure - which is much more intuitive.

If you choose this path, it is a good idea to use Composer , which can generate an autoload file and facilitate some aspects of your application.

    
07.01.2015 / 12:28
0

Maybe that will help you. In the php set_include_path () checks the first path, and if it does not find it, check the following path, until it either finds the included file or returns with a warning or an error. You can modify or define its include path at runtime using set_include_path (). See:

set_include_path(get_include_path() . PATH_SEPARATOR . 'diretorio');

See this example

But you also need to know the php autoload ().

    
07.01.2015 / 11:17