Include_once and right directories - php

Asked

Viewed 773 times

0

I’m having trouble with include regarding directories, because when I call a class from another directory that contains another include the paths are different. I need to know if there’s any way to unify these includes and always call them the same way, does anyone have any idea?

  • Give examples of what happens.

  • Or you add in includepath or uses some sort of define(_ROOT_, '/caminho/padrao'), and includes files always using include _ROOT_ . "/caminho/arquivo.php";.

2 answers

1


If you don’t use namespaces, the best way is to always take into account the absolute path of the system files, and not the relative paths - that is, the path of one file relative to another.

Also, always use the following magic constants in order to facilitate the inclusion of 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 PHP version 5.3 or higher, it’s suddenly worth starting to think about namespaces. So, instead of including the files manually, the organization of the classes takes into account the structure of directories - which is much more intuitive.

If you choose this path, it is a good use Composer, that can generate an autoload file and facilitates some aspects of your application development.

  • A separate detail: the magic constant (http://php.net/manual/en/language.constants.predefined.php) __DIR__ is only available from PHP 5.3. The best option to increase portability is to use dirname(__FILE__) instead of __DIR__.

0

Maybe this will help you. In php set_include_path() it checks the first path, and if it does not find it, check the following path, until it is either locate the included file or returns with a warning or an error. You can modify or define your 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 native php autoload().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.