Viewed   66 times

Anonymous functions are available from PHP 5.3.
Should I use them or avoid them? If so, how?

Edited; just found some nice trick with php anonymous functions...

$container           = new DependencyInjectionContainer();
$container->mail     = function($container) {};
$conteiner->db       = function($container) {};
$container->memcache = function($container) {};



Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:

$arr = range(0, 10);
$arr_even = array_filter($arr, function($val) { return $val % 2 == 0; });
$arr_square = array_map(function($val) { return $val * $val; }, $arr);

Otherwise you would need to define a function that you possibly only use once:

function isEven($val) { return $val % 2 == 0; }
$arr_even = array_filter($arr, 'isEven');
function square($val) { return $val * $val; }
$arr_square = array_map('square', $arr);
Tuesday, October 25, 2022

Yes, true anonymous functions (closures) are only available from PHP 5.3, however you can still create an anonymous function in earlier versions of PHP using the create_function() call, which can be used with array_walk(). Something like:

array_walk($myArray, create_function('&$value,$key', '$value = '"'.$value.'"';'));
Sunday, July 31, 2022

Just urlencode the string desired as a filename. All characters returned from urlencode are valid in filenames (NTFS/HFS/UNIX), then you can just urldecode the filenames back to UTF-8 (or whatever encoding they were in).

Caveats (all apply to the solutions below as well):

  • After url-encoding, the filename must be less that 255 characters (probably bytes).
  • UTF-8 has multiple representations for many characters (using combining characters). If you don't normalize your UTF-8, you may have trouble searching with glob or reopening an individual file.
  • You can't rely on scandir or similar functions for alpha-sorting. You must urldecode the filenames then use a sorting algorithm aware of UTF-8 (and collations).

Worse Solutions

The following are less attractive solutions, more complicated and with more caveats.

On Windows, the PHP filesystem wrapper expects and returns ISO-8859-1 strings for file/directory names. This gives you two choices:

  1. Use UTF-8 freely in your filenames, but understand that non-ASCII characters will appear incorrect outside PHP. A non-ASCII UTF-8 char will be stored as multiple single ISO-8859-1 characters. E.g. ó will be appear as ó in Windows Explorer.

  2. Limit your file/directory names to characters representable in ISO-8859-1. In practice, you'll pass your UTF-8 strings through utf8_decode before using them in filesystem functions, and pass the entries scandir gives you through utf8_encode to get the original filenames in UTF-8.

Caveats galore!

  • If any byte passed to a filesystem function matches an invalid Windows filesystem character in ISO-8859-1, you're out of luck.
  • Windows may use an encoding other than ISO-8859-1 in non-English locales. I'd guess it will usually be one of ISO-8859-#, but this means you'll need to use mb_convert_encoding instead of utf8_decode.

This nightmare is why you should probably just transliterate to create filenames.

Monday, August 8, 2022

When should I use an exception?

You use an exception to indicate an exceptional condition; that is, something which prevents a method from fulfilling its contract, and which shouldn't have occurred at that level.

For example, you might have a method, Record::save(), which saves changes to a record into a database. If, for some reason, this can't be done (e.g. a database error occurs, or a data constraint is broken), then you could throw an exception to indicate failure.

How do I create custom exceptions?

Exceptions are usually named such that they indicate the nature of the error, for example, DatabaseException. You can subclass Exception to create custom-named exceptions in this manner, e.g.

class DatabaseException extends Exception {}

(Of course, you could take advantage of inheritance to give this exception some additional diagnostic information, such as connection details or a database error code, for example.)

When shouldn't I use an exception?

Consider a further example; a method which checks for file existence. This should probably not throw an exception if the file doesn't exist, since the purpose of the method was to perform said check. However, a method which opens a file and performs some processing could throw an exception, since the file was expected to exist, etc.

Initially, it's not always clear when something is and isn't exceptional. Like most things, experience will teach you, over time, when you should and shouldn't throw an exception.

Why use exceptions instead of returning special error codes, etc?

The useful thing about exceptions is that they immediately leap out of the current method and head up the call stack until they're caught and handled, which means you can move error-handling logic higher up, although ideally, not too high.

By using a clear mechanism to deal with failure cases, you automatically kick off the error handling code when something bad happens, which means you can avoid dealing with all sorts of magic sentinel values which have to be checked, or worse, a global error flag to distinguish between a bunch of different possibilities.

Monday, September 12, 2022

Anonymous functions is a feature added in 5.3

For earlier versions, create a named function and refer it by name. Eg.:

function file_check_method_func($n) {
    $n = absint($n);
    if(1 !== $n) { $n = 0; }
    return $n;
$valid['file_check_method'] = array_map('file_check_method_func', $input['file_check_method']);

or inside a class:

class Foo {
  protected function file_check_method_func($n) {
    $n = absint($n);
    if(1 !== $n) { $n = 0; }
    return $n;
  function validate($input) {
    $valid = array();
    $valid['file_check_method'] = array_map(array($this, 'file_check_method_func'), $input['file_check_method']);
    return $valid;

I would strongly suggest not to rely on create_function.

Sunday, September 4, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :