PHP: Writing a Package

By Xah Lee. Date:

A collection of functions can be written and saved into a file. This file can then be loaded using require().

For example, save the following in a file and name it “myPackage.php”.

<?php
function ff($x) {
  return($x+1);
}
?>

Now, eval the following code:

<?php
require("myPackage.php");
echo ff(3); # prints 4
?>

“require()” works as if the whole file's content is inserted in-place.

As of PHP 5.2.4 (2007-08), there is no namespace mechanism for importing functions or packages.