Why use include_once when i can just simply type it once

528 Views Asked by At

include_once is self explanatory I understand perfectly how it works. I get that it will only include that include ONE TIME. GREAT !!! :)

My question is... If i only want that include ONE TIME on my page why am I having to write include_once when I could just simply only write the include one time in the first place. I'm sure there's a good reason why it would appear twice but the only examples I'm finding is someone typing the same include two times and I don't get why you'd go through the hassle of typing it twice but including the word "_once" so it only runs one time.

thanks.

2

There are 2 best solutions below

0
On

One example where the files could call include twice could be protected pages or parent pages (dashboards, etc.) that might be including several "child" pages which might already have this code included.

Example:

content1.php

<?php
  include_once 'require_login.php';      //Protect content1.php
?>
<html>...

content2.php

<?php
  include_once 'require_login.php';      //Protect content2.php
?>
<html>...

Now - parent "dashboard" - let's call it view_dashboard.php might be including several files - all of which already have a copy of the same require_login.php protective script.

<?php
   include_once 'require_login.php' //Protect the dashboard.
   include 'content1.php'           //No conflict - thanks to include_once
   include 'content2.php'           //No conflict - thanks to include_once
   //...

include_once is more slow than include so use it sparingly.

1
On

Imagine you include a file that declares a variable. You included that file because it is part of a library you need to use.

Now imagine you include another file because you need another library. But what if that new file is including the same file you included before, because the second library needs the first library?

Then you would have the first file included twice, and you didn't even know.

That's why.

And, by the way: require_once is better than include_once.