PHP Include & Namespace

Include another PHP File using require or include

require '';              # Include a file within another PHP file
                                        # Throw a fatal error if the file not exist

include '';               # Only give a warning if the file not exist
  • require will throw a fatal error if the file is not presence

Only include the file once

require_once '';                # Only include the file if it is not already included

include_once '';

Namespace (PHP 5.3 or above)

Define a namespace

namespace Web\Core;

const MESSAGE = 'hello';
function m1() {}
class Obj1
   static function get_instance() {}

Accessing a namespace object

namespace Web;

include 'file1.php';

\Web\Core\m1();                           # access a method in another namespace
\Web\Core\Obj1::get_instance();           # static method
\Web\Core\MESSAGE;                        # constant

Core\m1();                                # Relative to current namespace

$class = '\Web\Core\Obj1';
$obj = new $class;

$f = \fopen("c:\\test.txt", "r");         # \fopen: Access fopen in global namespace

Using alias instead of full path

namespace Web;

include 'file1.php';

use \Web\Core\Obj1 as Obj1;               # alias Obj1 as \Web\Core\Obj1

# use \Web\Core\Obj1;                     # same

use \Web\Core

$a = new Obj1;
$a = new Core\Obj1;

  • PHP falls back to global functions or constants if the function or constant is not found in the current namespace