Closing in PHP ... what, actually, are they and when do you need to use them?

So, I program in a good, relevant, object-oriented style. I regularly use various aspects of OOP that PHP implements, but I wonder when I need to use closure. Any experts who can shed light on when it would be useful to close?

+60
closures oop php
Sep 28 '08 at 21:06
source share
6 answers

PHP will support closure initially in 5.3. Closing is good when you want to use a local function that is used only for a small, specific purpose. Good example: RFC to close .

function replace_spaces ($text) { $replacement = function ($matches) { return str_replace ($matches[1], ' ', ' ').' '; }; return preg_replace_callback ('/( +) /', $replacement, $text); } 

This allows you to define the replacement function locally inside replace_spaces() so that it is not:
1) Global namespace attenuation
2) By giving people three years down, wonder why there is a global function that is used only within one other function.

It keeps things organized. Notice how the function itself does not have a name; it is simply defined and assigned as a reference to $replacement .

But remember, you need to wait for PHP 5.3 :)

+61
Sep 30 '08 at 14:41
source share

When you need a function in the future that performs the task that you have solved now.

For example, if you are reading a configuration file, and one of the parameters tells you that hash_method for your algorithm is multiply , not square , you can create a closure that will be used wherever you need a hash.

Closing can be created (for example) config_parser() ; it creates a function called do_hash_method() using the local to config_parser() variables (from the configuration file). Whenever do_hash_method() is called, it has access to the variables in the local area of config_parser() , even if it is not called in this area.

Hope a good hypothetical example:

 function config_parser() { // Do some code here // $hash_method is in config_parser() local scope $hash_method = 'multiply'; if ($hashing_enabled) { function do_hash_method($var) { // $hash_method is from the parent local scope if ($hash_method == 'multiply') return $var * $var; else return $var ^ $var; } } } function hashme($val) { // do_hash_method still knows about $hash_method // even though it not in the local scope anymore $val = do_hash_method($val) } 
+14
Sep 28 '08 at 21:23
source share

Besides the technical details, closure is a fundamental prerequisite for a programming style called function-oriented programming. Closing is used in much the same way that you use an object for object-oriented programming; It binds data (variables) together with some code (function), which can then be transferred to another place. Thus, they affect how you write programs, or - if you do not change the way you write your programs - they have no effect whatsoever.

In the context of PHP, they are a little strange, since PHP is already heavy on a class-based, object-oriented paradigm, as well as an older procedural one. Typically, languages ​​with closure have full lexical coverage. To maintain backward compatibility, PHP will not get this, so this means that the closure here is slightly different than in other languages. I think we have yet to see how they will be used.

+13
Sep 28 '08 at 22:22
source share

I like the context provided by the troelskn post. When I want to do something like a Dan Udey example in PHP, I use the OO strategy template. In my opinion, this is much better than introducing a new global function whose behavior is determined at runtime.

http://en.wikipedia.org/wiki/Strategy_pattern

You can also call functions and methods using a variable containing the method name in PHP, which is great. so another Dan example would be something like this:

 class ConfigurableEncoder{ private $algorithm = 'multiply'; //default is multiply public function encode($x){ return call_user_func(array($this,$this->algorithm),$x); } public function multiply($x){ return $x * 5; } public function add($x){ return $x + 5; } public function setAlgorithm($algName){ switch(strtolower($algName)){ case 'add': $this->algorithm = 'add'; break; case 'multiply': //fall through default: //default is multiply $this->algorithm = 'multiply'; break; } } } $raw = 5; $encoder = new ConfigurableEncoder(); // set to multiply echo "raw: $raw\n"; // 5 echo "multiply: " . $encoder->encode($raw) . "\n"; // 25 $encoder->setAlgorithm('add'); echo "add: " . $encoder->encode($raw) . "\n"; // 10 

of course, if you want it to be available everywhere, you could just make everything static ...

+8
Sep 29 '08 at 0:44
source share

Closing is basically a function for which you write a definition in one context, but execute it in another context. Javascript helped me a lot in this because they are used in JavaScript everywhere.

In PHP, they are less efficient than in JavaScript, due to differences in the volume and availability of "global" (or "external") variables from within functions. However, starting with PHP 5.4, closures can access this object when launched inside the object, which makes them much more efficient.

This is what closure is, and that should be enough to understand what is written above.

This means that it should be possible to write a function definition somewhere and use the $ this variable in the function definition, then assign the function definition to a variable (others gave examples of syntax), then pass this variable to the object and call it in the context of the object, the function can then access and manipulate the object via $ this, as if it were only one of its methods, when in fact it is not defined in the class definition of this object, but somewhere else.

If this is not very clear, then do not worry, it will become clear after you start using them.

+1
Aug 25 '14 at 18:46
source share

Here are examples of closure in php

 // Author: HishamDalal@gamil.com // Publish on: 2017-08-28 class users { private $users = null; private $i = 5; function __construct(){ // Get users from database $this->users = array('a', 'b', 'c', 'd', 'e', 'f'); } function displayUsers($callback){ for($n=0; $n<=$this->i; $n++){ echo $callback($this->users[$n], $n); } } function showUsers($callback){ return $callback($this->users); } function getUserByID($id, $callback){ $user = isset($this->users[$id]) ? $this->users[$id] : null; return $callback($user); } } $u = new users(); $u->displayUsers(function($username, $userID){ echo "$userID -> $username<br>"; }); $u->showUsers(function($users){ foreach($users as $user){ echo strtoupper($user).' '; } }); $x = $u->getUserByID(2, function($user){ return "<h1>$user</h1>"; }); echo ($x); 

Output:

 0 -> a 1 -> b 2 -> c 3 -> d 4 -> e 5 -> f ABCDEF c 
0
Aug 28 '17 at 14:35
source share



All Articles