Hacker News new | ask | show | jobs
by chriswarbo 4348 days ago
> To me it screams wrongly used PHP.

Of course it's wrongly used, since it doesn't work (hence my request to make it work).

The issue is not whether we should write such code now (we obviously shouldn't, since we'll hit all kinds of language problems); it's whether we'd like to write such code in the future (in which case we need to fix those problems now). Personally, I would like to avoid redefining built-in capabilities over and over.

As for what I'm trying to achieve, the same as everyone else: clean, understandable, maintainable code.

Here's something I ran across this week. I'm instantiating a class $class (read from a config file) and need to inject dependencies ($dep_classes, read from a config file) into the constructor. How to do it?

    $deps = [];
    foreach ($dep_classes as $dep_class) {
      $deps[] = new $dep_class;
    }
    $instance = new $class(...$deps);
It works, but turning $dep_classes into $deps is clearly a use-case for array_map. We shouldn't reinvent the wheel:

    $deps = array_map(function($dep_class) { return new $dep_class; }, $dep_classes);
    $instance = new $class(...$deps);
Again, it works, but that anonymous function is pretty horrible; we might have been better off with the loop!

However, it's clear that, again, we're reinventing the wheel. array_map passes the class names to its callback, so why are we passing them to "new" ourselves?

    $deps = array_map('new', $dep_classes);
    $instance = new $class(...$deps);
This gives an error, since "new" is an operator. Does this scream of "wrongly used PHP", or is it a problem with the language that would be nice to fix? I'd say the latter, since at the moment we're forced to do one of two things:

- Use a foreach loop to duplicate the functionality of array_map. - Define a new function which behaves exactly like "new".

Perhaps 15 years with PHP has given you a "gut feeling" to avoid programming styles which will inevitably run into problems; I've certainly got such a feeling after 4 years. While avoiding those problems is useful to get a job done today, it would be even better if we didn't have to worry about them tomorrow.

There's no point adding features like array_map, anonymous functions, etc. to the language if we all have to learn to avoid them to avoid parser errors.