Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Shon Levi
Shon Levi
6,036 Points

Differences between DIE/EXIT & INCLUDE/REQUIRE/INCLUDE_ONCE/REQUIRE_ONCE

Hey you all, I'm working and programming PHP codes but I still don't get the differences between some of the commands - please try to explain me the differences of them:

1 - die & exit

2 - how to write: "die();" or "die;" / "exit();" or "exit;"?

3 - include & require

4 - include & include_once // require & require_once

5 - how to write: "include('...');" or "include '...';" // "require('...');" or "require '...';"

Thanks !!!

1 Answer

Codin - Codesmite
Codin - Codesmite
8,600 Points

1 - die & exit

die and exit functions are aliases of eachother and function the same.

2 - how to write: "die();" or "die;" / "exit();" or "exit;"?

<?php
die("Error");

fwrite(STDERR, "Error");
exit(1);
?>

3 - include & require

require is identical to include except upon failure it will also produce a fatal level error (E_COMPILE_ERROR). In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

4 - include & include_once // require & require_once

This one is fairly simple, require_once and include_once will only include the file once. For example if you had a for loop like this:

<?php
for ($x = 0; $x <= 10; $x++) {
    include_once('example.php');
    echo $x;
}
?> 

It will only include the file on the first loop.

Where as:

<?php
for ($x = 0; $x <= 10; $x++) {
    include('example.php');
    echo $x;
}
?> 

Will include the file on every loop.

5 - how to write: "include('...');" or "include '...';" // "require('...');" or "require '...';"

Either way is valid syntax, parenthesis are used for grouping.

For example:

<?php
   include('dog.php');
   include 'dog.php';
   include('dog.php') . 'cat.php';
   include 'dog.php' . 'cat.php';
?>