0

I have a doubt that makes me very confused, it's about require_once. I saw a question on StackOverflow about it but I'm still not sure I understand...

I know the difference between require and include is that using require, the script will issue a fatal error and stop execution, while include does not. But there is something that I have been asking myself, the true meaning of _once, most people say something like: PHP will check if the file has already been included, and if so, not include (require) it again.
How will the script be required only once? I don't understand this, because in my point of view PHP scripts are not like CSS that our browser downloads and is saved on the machine, so then not needing to download again, I think that every time a PHP script is executed, it will do its job again, there is no way to understand that it has already been required just as browsers understand that we have already downloaded CSS files.

What is the real meaning of _once? And could someone please give me an example, because I don't really understand it, I'm a beginner, I don't even know if I'm asking a proper question

If possible demonstrate some code so that I finally understand

1 Answers1

1

Imagine this scenario. It's nice to be able to include the same file as you can use it multiple times with different outcomes:

display.php

echo $var;

index.php

$var = 'Hello ';
include('display.php');

$var = 'World ';
include('display.php');

This outputs:

Hello World

However, sometimes this will cause problems. This could be an include in different files, so you need to include_once, but to illustrate:

functions.php

function display($var) { echo $var; }

index.php

include('functions.php');
display('Hello ');

  //more code

include('functions.php');
display('World ');

Generates a fatal error:

Fatal error: Cannot redeclare display() (previously declared in index.php:1) in index.php on line 6

So if you have hundreds of files and some include others depending on some logic/program flow but some files can only be included once (as seen above) then that is the use case.

Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87