Http Hobo

Another blog with web-development tips’n’tricks. | About me

Why I don’t like PHP: inconsistency

There are tons of programming languages nowadays. Some of them are low-level, some of them high-level. Some of them have more features and so-called syntax-sugar, some of them – less. Some of them have more extensions and libraries, some of them – less. Some of them are easier to learn, some of them harder. What I want to say is that it doesn’t really matter. The most pragmatic approach is to use the one which you are going to be paid for.

However, good language makes your life easier. Besides all the things said above, it should be intuitively understandable. You might not know how to write some things, but with a good language you would have an idea. This is what in my opinion PHP is lack of.

Consistency is one of the key pillars of intuitive understanding. If you know that string functions always start with str_ prefix, and you are looking into some new function, you would just type str_ in your IDE and wait for autocompletion tips. Seriously, if a function is named well, you would find it. But not in PHP. In PHP string functions start with str_, str or often have no prefix.

Function replacing a substring into something else is str_replace(). Functions trimming garbage are trim(), ltrim() and rtrim(). If you want to know string length, you go with strlen() function. You can’t keep this in mind, you can’t intuitively find needed function, so often you just have to google it.

I remember once my boss told me that the better interface of an application is, the less calls he will have to the support, which leads to less operational costs. From this point of view this PHP naming hell is very unfortunate.

Now let’s take a look on array functions. Naming is better there, most of the functions start with array_ prefix. But don’t relax, it’s not over yet. Let’s say we have an array of some objects and we need to have an array of their IDs. We go with array_map() function:

$objects = array($var1, $var2, ..., $varN);
$ids = array_map(function ($obj) { return $obj->id; }, $objects);

Pretty clear, isn’t it?. Function array_map() receives first parameter as a callback function, second as an array. Now when we have an array of IDs, let’s say we want to filter it and return only those IDs which are less than 10 (I know, it is quite stupid, can’t imagine why I would need to do this, but whatever):

// Now knowing array_map() function you write the following:
$filtered_ids = array_filter(function($id) { return $id >= 10; }, $ids);

Aaaaaand... this will not work! Because array_filter() receives an array as the first parameter, callback should be the second one:

$filtered_ids = array_filter($ids, function($id) { return $id >= 10; });

What the hell? How such inconsistencies would happen?