DEV Community

Discussion on: What language features/concepts do insiders of the language love and outsiders hate?

Collapse
 
geoff profile image
Geoff Davis

Love first class functions. I miss that perhaps the most when programming in the other scripting language I use the most: PHP.

Collapse
 
alephnaught2tog profile image
Max Cerrina

...doesn't PHP have first class functions? I thought first-class functions meant you could use them as arguments or assign them to a variable, e.g.:

<?php

$some_function_holding_var = 
        function($inner_arg) 
        { 
            echo "I'm a function saying $inner_arg!"; 
        };

$some_function_holding_var("hello");

// okay, not very random
$random_array = [1,2,3,4];

array_walk($random_array, 
        function(&$number) 
        {
            ++$number;
        });

print_r($random_array);

$pick_func_based_on_time = 
    function ($some_time) 
    {
        $even_function = function () {echo "even";};
        $odd_function = function () {echo "odd";};

        switch ($some_time % 2) 
        {
            case 0:
                return $even_function;
                break;
            case 1:
                return $odd_function;
                break;
            default:
                echo "I broke math...";
                break;
        }
    };

$chosen_function = $pick_func_based_on_time(microtime(true));

$chosen_function();

I'm honestly just curious as to if there's a meaning of first-class functions I'm missing. (And enjoyed the chance to do ridiculous code stuff.)

Thread Thread
 
promisetochi profile image
Promise Tochi

That's pretty much it. First class function means you can use functions wherever normal language primitives will go. It can be returned, used in expressions...