Friday 26 June 2015

PHP Include Vs Require

One of the great features of PHP is the ability to include code from other files into other PHP files. Ok, big whoop, you’re probably thinking. You may be right, but this is an important feature because it is by using this approach that the foundations of code organization and reuse are born. Let’s keep it right down to basics at this juncture. Forget frameworks, Composer, and any other advanced methods you might already be using. We’re going back to procedural Function Based style right about now. Imagine you have a page on your website and you just created a killer function that does some really awesome processing of the data you’re working with. Now, two months later, in an entirely different section of the website and codebase you have a need to process that data the very same way your original killer function did. Are you going to write that function again? You might, if you’re just starting, like all of us have done! A better way however would be to include or require a file which contains the function code you would like access to. Maybe your function is 30 lines long. In this new file, you can include the file on one line, then call it on the next so to speak. 2 lines vs 32 lines is a nice ROI. Not only is the lack of typing a motivating factor, but what if you find a bug in your super awesome function a few months down the line. Say you had pasted that function code in ten different PHP files within your website. Guess what Johnny, open up your favorite editor and get ready for some mind numbing code maintenance because you are now going to have to fix that bug in 10 different places. You know what, Funk That. We’re going to make sure that doesn’t happen again using the techniques here.

1. include($path)

There is one thing we didn’t mention yet about this fantastic function. This useful function is not only for including PHP Code, you can place whatever you like in the file to be included, such as HTML. Pretend your awesome page makes use of some common elements in the head section, and you have 10 different pages that all use the same head data. You don’t need to reinvent the wheel each time! Let’s see how this works.

yourawesomepage.php

Now, rather than manually typing out all of that data in the head section into all of your other pages, lets create a DRY Maker and include that instead.

the_dry_maker.php

Now, when you create your other awesome page, you can do so with style and grace just like so.
Notice that the Dry Maker file doesn’t even have any PHP in it. We are simply using PHP in the includer file to include non PHP text from the includee file. What this means is that when the include function runs, PHP essentially shuts off inside of it so you can import non PHP data. This also brings up the point that if you want to include PHP from the other file, you’ll need to make sure that you are turning PHP back on in that file. Let’s see this by way of including an example function.

yourawesomepage.php

the_dry_maker.php

Keeping It DRY Since A Long Time Ago. © ® ™
You know what Jim? You are Awesome, give me a high five!
Nice! You can now include The Dry Maker file on any page of your website, and give a high five to anyone you feel like, no need to write a new function every time. Now right now you might just be giving a high five – but what happens once you start saving the world? Now you can begin to see the power of the include function.

2. require($path)

When we look at require vs include, it might seem like they are basically the same. In fact, PHP require and PHP include do all of the same things, except with the following difference. If require can’t find the file you wish to load, PHP will raise a fatal error and script will come to a screeching halt. In some cases this might make sense, but in others, not so much. In the prior example, using include makes sense. It’s great to give high fives, but probably not mission critical to our application. So if we fail to include The Dry Maker file, the page will still try to finish executing. Now since we try to call a function on the page which is referencing a function definition from another file which is now not included we’ll get an error from that. The key point though is that the include itself will not cause a failure. On the other hand, lets say your database driven site has all of its database functions in a file like database_funcs.php. This is an important piece of code, so much so that your site would not be able to run without it. In this case, require makes sense. Let’s see this in action, we’ll change the code in yourawesomepage.php to have a typo for the file we’re looking for. Then we’ll test out the require vs include and see what happens.

require

  • ( ! ) Warning: require(tthe_dry_maker.php): failed to open stream: No such file or directory in C:wampwwwbootstrapsandboxyourawesomepage.php on line 16
  • ( ! ) Fatal error: require(): Failed opening required ‘tthe_dry_maker.php’ (include_path=’.;C:phppear’) in C:wampwwwbootstrapsandboxyourawesomepage.php on line 16

include

  • ( ! ) Warning: include(tthe_dry_maker.php): failed to open stream: No such file or directory in C:wampwwwbootstrapsandboxyourawesomepage.php on line 16
  • ( ! ) Warning: include(): Failed opening ‘tthe_dry_maker.php’ for inclusion (include_path=’.;C:phppear’) in C:wampwwwbootstrapsandboxyourawesomepage.php on line 16
  • ( ! ) Fatal error: Call to undefined function highfive() in C:wampwwwbootstrapsandboxyourawesomepage.php on line 17
See the difference? With the require, the script halts right in its tracks as soon as it can’t find the file, and a fatal error is thrown. Conversely, the include only throws a warning when it can’t find the file. Later on on in the page however when we try to call the highfive function, a fatal error is thrown since you can’t call a function that is not defined.

3. include_once($path)

In order to show the difference between include and include_once, let’s modify yourawesomepage.php to make multiple include calls to the same dry maker file we’ve been working with to see what happens. Then we’ll try the same test with include_once and discuss the results.

yourawesomepage.php

Page Output

  • Keeping It DRY Since A Long Time Ago. © ® ™
  • You know what Jim? You are Awesome, give me a high five!
  • ( ! ) Fatal error: Cannot redeclare highfive() (previously declared in C:wampwwwbootstrapsandboxthe_dry_maker.php:13) in C:wampwwwbootstrapsandboxthe_dry_maker.php on line 16
What happens here is that the page runs just fine until it hits the second include statement. At that point, include pulls in the file and PHP sees that highfive is getting declared again. This is a big no no and a fatal error is thrown. Now let’s change the code to use include_once.

yourawesomepage.php

Page Output

  • Keeping It DRY Since A Long Time Ago. © ® ™
  • You know what Jim? You are Awesome, give me a high five!
  • You know what Jim? You are Awesome, give me a high five!
Excellent, no errors! You see that when we use the include_once statement, we no longer get the fatal error and the page runs perfectly. Why is that? This is because include_once adds the original path to an array, and if it sees that path attempt to be included again it will ignore it. So in this code above, when the second include_once statement is hit, PHP now knows that the path provided was already included so it ignores it. This way, there is never any attempt to redeclare the highfive function, and everything operates smoothly.

4. require_once($path)

Last up in our list of brilliant functions within PHP is the require_once function. This option has the properties of the original require function, in addition to the fact that just like include_once, multiple attempts to require the same file will be ignored. All 4 have specific applications as you can see, so now you know which is best to use for your applications.

The Brilliant Takeaway

These are simple functions in PHP however they are incredibly powerful. What is something that is simple, yet incredibly powerful? That’s right, it’s brilliant. We saw how we can use the php include to include html by specifying the include path to the file in question. This can be used for a header, or a footer, and it all works like magic on the server side. By looking at php require vs php include, we also learned the differences of how they may or may not throw a fatal error and when best to use them. The same can be said for the php include_once vs php require_once.

0 comments:

Post a Comment