Difference between require, include, require

In PHP:

  • When should I use require vs. include ?
  • When should I use require_once vs. include_once ?

  • There are require and include_once as well.

    So your question should be...

  • When should I use require vs. include ?
  • When should I use require_once vs. require
  • The answer to 1 is described here.

    The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

    The answer to 2 can be found here.

    The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.


    Use

  • require
    when the file is required by your application, eg an important message template or a file containing configuration variables without which the app would break.

  • require_once
    when the file contains content that would produce an error on subsequent inclusion, eg function important() { /* important code */} is definitely needed in your application but since functions cannot be redeclared should not be included again.

  • include when the file is not required and application flow should continue when not found, eg
    great for templates referencing variables from the current scope or something

  • include_once
    optional dependencies that would produce errors on subsequent loading or maybe remote file inclusion that you do not want to happen twice due to the HTTP overhead

  • But basically, it's up to you when to use which.


    My suggestion is to just use require_once 99.9% of the time.

    Using require or include instead implies that your code is not reusable elsewhere, ie that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

    If you are require/including code that executes on the spot, that's procedural code, and you need to get to know a new paradigm . Like object oriented programming, function-based programming, or functional programming.

    If you're already doing OO or functional programming, using include_once is mostly going to be delaying where in the stack you find bugs/errors. Do you want to know that the function do_cool_stuff() is not available when you go to call for it later, or the moment that you expect it to be available by requiring the library? Generally, it's best to know immediately if something you need and expect isn't available, so just use require_once .

    Alternatively, in modern OOP, just autoload your classes upon use.

    链接地址: http://www.djcxy.com/p/9952.html

    上一篇: 新的自我与新的静态

    下一篇: 要求之间的区别,包括,要求