Capítulo 1: Aplicando la inteligencia emocional en el aula
1.2 Diagnósticos:
1.2.2 Diagnóstico Liceo Emilia Toro de Balmaceda
Closures arrived in PHP 5.3, which means that they’re fairly recent! They were a game-changer for the PHP world, because they allow you to pass small sections of logic into functions. That’s right, you can pass a Closure to a function. Let’s see this in action.
Oh, by the way, did I mention that you can type-hint a Closure? Simply place the word Closure before a parameter to ensure that only a closure is passed as a parameter to the method. If you were to callget_type()on a Closure, you’d receive the valueClosure. It’s a complex object in PHP. We’ll see other objects of this type later.
Where were we? Oh yes, an example! Example 05: Type-hinting a Closure. 1 <?php
2
3 // Create a math function.
4 function math(Closure $type, $first, $second) { 5
6 // Execute the closure with parameters
7 return $type($first, $second); 8 }
Okay, what’s going on here?
First of all, we’ve got a function calledmath(), but it’s not doing a lot of math()at the moment. It receives a type-hinted Closure, and two other variables as parameters. Well, we’re not going to be able to call it without a Closure, are we? Let’s make a few Closures so that we can test it. We’ll create Closures that perform mathematical operations. I know, I know. There’s a lot of math, isn’t there? I promise to keep it basic!
Closures 89
Example 06: Two Closures. 1 <?php
2
3 // Create a math function.
4 function math(Closure $type, $first, $second) { 5
6 // Execute the closure with parameters
7 return $type($first, $second); 8 }
9
10 // Create an addition closure.
11 $addition = function ($first, $second) { 12
13 // Add the values.
14 return $first + $second; 15 };
16
17 // Create an subtraction closure.
18 $subtraction = function ($first, $second) { 19
20 // Subtract the values.
21 return $first - $second; 22 };
We’ve defined two Closures bound to the variables $addition and $subtraction. They both receive two parameters, and perform subtraction or addition on these values. Let’s try to use them with ourmath()function, shall we?
Example 07: Passing Closures to functions. 1 <?php
2
3 // Create a math function.
4 function math(Closure $type, $first, $second) { 5
6 // Execute the closure with parameters
7 return $type($first, $second); 8 }
9
10 // Create an addition closure.
11 $addition = function ($first, $second) { 12
13 // Add the values.
14 return $first + $second; 15 };
16
17 // Create an subtraction closure.
18 $subtraction = function ($first, $second) { 19
20 // Subtract the values.
21 return $first - $second; 22 };
23
24 // Execute math function.
25 echo math($addition, 2, 2); 26 echo PHP_EOL; // New line!
27 echo math($subtraction, 5, 3);
The PHP_EOL is a constant that will be replaced with a newline character that’s compatible with the current operating system. It’s super handy!
We call the math() function twice with a different assigned Closure each time, providing integers, and separating the calls with a newline character using the PHP_EOLconstant. Let’s take a look at the output.
Example 08: Output. 1 4
2 2
Great! By passing a different Closure to outmath()function, we’ve changed the way that it works. For homework, why don’t you try changing the above code to include multiplication and division functionality? Here’s a hint, you’re going to want more Closures!
15. Includes
You’ve been learning PHP for a while now, it’s time to talk about your future. You’re in a committed relationship with PHP. You have matching his and hers dressing gowns. You might be thinking about marriage already. You’re probably going to want to write future applications with PHP, aren’t you?
Include
It would be a shame if you had to keep writing the same code over and over again, wouldn’t it? I mean, it was fun to write, but it would slowly wear away at you. Let’s imagine that you have the following function.
Example 01: A familiar function. 1 <?php
2
3 function welcome($name) {
4 return "Welcome, {$name}!"; 5 }
Ah! The oldwelcome() function. It never gets old! We’re gonna need this in a lot of our applications. After all, if we don’t welcome our users, they might get angry at us! We can use theincludestatement to make this code somewhat re-usable. First let’s put the function in it’s own file. We’ll call itwelcome.php. We’ll put the same code inside.
Example 02: Here it is again. 1 <?php
2
3 function welcome($name) {
4 return "Welcome, {$name}!"; 5 }
Now then, let’s create a new file, called program.php. We’ll place this file next to thewelcome.phpfile. We want to use thewelcome() function within this file, so let’s includethewelcome.phpfile. Confused? Let’s see theprogram.phpfile.
Example 03: Including a file. 1 <?php
2
3 include 'welcome.php'; 4
5 echo welcome('Tamas');
We useinclude()to include thewelcome.phpfile. It’s like PHP is copying and pasting the code inwelcome.phpto where we’ve put theincludestatement. We can now use thewelcome()function like before.
Theincludestatement is followed by the path to the file that we want to include. This path is relative to the file that you execute with thephpcommand. If ourwelcome.php file was located in a subfolder, then we could use slashes/like we would in a unix filesystem to denote its location.
Example 04: Including within subdirectories. 1 <?php
2
3 include 'foo/bar/baz/welcome.php';
You can use as many includes as you like! Go ahead and modularise your code into re-usable files. You can alsoincludefrom your included files. Kind of like that dream movie.
You can use the __DIR__ constant to refer to the directory that the current file is in. This can be useful wheninclude()ing other files!
Require
If you try toincludea file that doesn’t exist, then PHP will show a warning message, and continue executing. If this is a problem in our applications, we can use the requirestatement instead of theincludeto have PHP throw a fatal error when the file cannot be loaded.
The syntax is exactly the same as the include statement. Let’s load an imaginary file.
Includes 93
Example 05: Requiring a file. 1 <?php
2
3 require 'foo.php';
Let’s see what PHP has to say about the imaginaryfoo.phpfile, shall we? Example 06: Output.
1 Fatal error: require(): Failed opening required 'foo.php'
Great! That’s going to put an end to that program. Come back when the file exists, you crazy loon!