John Smith
John Smith

Reputation: 6207

Is it ok to use closures for the sake of encapsulation?

I was using a code like that:

$a = [];
$a['a'] = 1;
$text1 = [];
foreach ($b as $item)
{
    $text1[] = $item['1'];
}
$a['text1'] = implode(',', $text1);

$text2 = [];
foreach ($b as $item)
{
    $text2[] = $item['2'];
}
$a['text2'] = implode(',', $text2);

my colleague rewitten it like that:

$a = [];
$a['a'] = 1;
$a['text1'] = call_user_func(function() use ($b) {
    $text1 = [];
    foreach ($b as $item)
    {
        $text1[] = $item['1'];
    }
    return implode(',', $text1);
}();

$a['text2'] = call_user_func(function() use ($b) {
    $text2 = [];
    foreach ($b as $item)
    {
        $text2[] = $item['2'];
    }
    return implode(',', $text2);
}();

his reason: it increases encapsulation, and in my first example there will be "strolling" variables ($text1, $text2) unless I unset them.

Upvotes: 0

Views: 65

Answers (1)

localheinz
localheinz

Reputation: 9592

Yes, I agree with your colleague - it makes sense to use closures to encapsulate code.

However, the entire thing you have there can be simplified to this:

<?php

$a = [
    'a' => 1,
    'text1' => implode(',', array_column($b, '1')),
    'text2' => implode(',', array_column($b, '2')),
];

For reference, see:

Upvotes: 2

Related Questions