Organize Code

Source File

PHP

 

Defining module

PHP 5
// logger.php file

function err($msg){ print("ERR: " . $msg); }
function warn($msg){ print("WARN: " . $msg); }
function info($msg){ print("INFO: " . $msg); }

function logMsg($msg, $type) {
  switch($type) {
    case 0:
      err($msg);
      break;
    case 1:
      warn($msg);
      break;
    default:
      info($msg);
  }
}

Php code can be organized in separate PHP files, and then each file can be imported in other PHP files.

There are couple of ways to import a file in PHP:

  • include
  • include_once
  • require
  • require_once
 

Import using "include"

PHP 5
include './logger.php';

info('logger.php');  // INFO: logger.php

include lets you to import a file.

It is like you copy the whole file in place of the include statement.

If the file is missing, include will only warn you and the script will continue.

include_once can be used instead, if you want to make sure the file will not be imported for a second time.

include and include_once can be written in form of statement or function.

include './logger.php';
include('./logger.php');
 

Import using "require"

PHP 5
require './logger.php';

info('logger.php');  // INFO: logger.php

require lets you to import a file similar to include.

The only difference is, If the file is missing, require will error out and the script will stop.

require_once can be used instead, if you want to make sure the file will not be imported for a second time.

require and require_once can be written in form of statement or function.

require './logger.php';
require('./logger.php');