1.3. Loading Extensions

If the extension you need isn't built into PHP, you need to load it programmatically by using either the require() or include() functions. Both functions do essentially the same job — they act as placeholders for the extension you want to load.

For example, we create a small script like the following and call it message.php:

<?php
   $message = "Hello World!";
?>

message.php doesn't actually produce any output. It just initializes the variable $message. So you need to create a second script, called action.php:

<?php
   echo $message;
   include("./message.php");
   echo $message;
?>

The first echo statement produces a null character because you haven't defined the $message variable yet. The second echo statement prints out your message. The include() statement essentially cuts and pastes the code from the extension into the calling script. The code executes as if the script were written like this:

<?php
   echo $message;
   $message = "Hello World!";
   echo $message;
?>

The preceding example uses the include() statement. You could also use require(), which accomplishes the same task, except for the way it handles errors. If the extension you want to bring into your script doesn't exist or can't be found, require() throws a fatal error and crashes the entire application — not usually a good thing, especially in a production setting. The include() statement simply issues a warning and goes on as best it can.

NOTE

When your application gets more complex than just a few scripts ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.