PHP Include & Namespace

Include another PHP File using require or include

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

include 'option_lib.inc';               # 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 'file.inc';                # Only include the file if it is not already included

include_once 'file.inc';

Namespace (PHP 5.3 or above)

Define a namespace

file1.php
namespace Web\Core;

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

Accessing a namespace object

file2.php
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;

Core\m1();
  • PHP falls back to global functions or constants if the function or constant is not found in the current namespace