Closing objects inside arrays before PHP 5.3

I know that the following can be done with PHP 5.3 (anonymous functions), but is there a similar alternative in the old version of PHP (pre-5.3)?

$exampleArray = array( 'func' => function() { echo 'this is an example'; } 

Is it possible to do this using __call or casting a function as an object (object) in the first place? In addition, I tried to make the function anonymous by giving it a name, but this does not seem to work.

+4
source share
4 answers

If you want to create anonymous in PHP <5.3, you can use create_function . Also, information about callbacks is interesting here (it may be useful).

create_function

 # This (function in other variable is only for cleaner code) $func = create_function('', "echo 'This is example from anoymus function';"); $exampleArray = array( 'func' => $func ); 

But you can do the same liek code above with an alternative way:

 # Create some function function func() { # Do something echo 'This is example'; } # Save function name $func = 'func'; 

The code above creates a function that does something, then we save the function name in a variable (it can be passed as a parameter, etc.).

The calling function, when we know only its name:

First way

 $func(); 

Alternative

 call_user_func($func); 

So, an example that connects all of the above:

 function primitiveArrayStep(&$array, $function) { # For loop, foreach can also be used here for($i = 0; $i < count($array);$i++) { # Check if $function is callable if( is_callable($function) ) { # Call function $function(&$array[$i]); } else { # If not, do something here } } } 

And using the function above:

 $array = array('a', 'b', 'c'); $myFunction = create_function('&$e', '$e = $e . " and i was here";'); primitiveArrayStep($array, $myFunction); echo '<pre>'; var_dump($array); 

Return:

 array(3) { [0]=> string(16) "a and i was here" [1]=> string(16) "b and i was here" [2]=> string(16) "c and i was here" } 

References:

+9
source

Yes, you can create lamda functions from PHP up to 5.3 using create_function . It is not possible to create a closure , although your question is mentioned, but not actually used.

Closing is a lamda function that has access (closes) a variable from it, covering the scope:

 $t = new Thingy; $func = function( $y ) use( $t ) { //$t is available here when this function is called; } 

The lamda function is an anonymous function, useful for storing in a variable or passing as an argument, etc. You can use create_function() pre 5.3 as follows:

 $func = create_function( '$y', 'echo $y;' ); //similar to $func = function( $y ){ echo $y }; 
+6
source
 $exampleArray = array( 'func' => create_function('', 'echo "this is an example"'); ); 

create_function

+3
source

How to simply create a class with the func function as a class method? Will work before or after 5.3.

0
source

All Articles