0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

foreachの中身だけ違う関数が複数ある場合の共通化

Posted at

<?php
class SomeForeach
{
  const SOME_LIST = [
    ['key'=>1],
    ['key'=>3],
    ['key'=>5],
    ['key'=>7]];

  public static function newList()
  {
    $returnList = [];
    foreach(self::SOME_LIST as $v) {
      $returnList[] = $v['key'];
    }
    return $returnList;
  }

  public static function newList2()
  {
    $returnList = [];
    foreach(self::SOME_LIST as $v) {
      $returnList[] = $v;
    }
    return $returnList;
  }
}

var_dump(SomeForeach::newList());
var_dump(SomeForeach::newList2());

class SomeForeach2
{
  const SOME_LIST = [
    ['key'=>1],
    ['key'=>3],
    ['key'=>5],
    ['key'=>7]];

  public static function newList()
  {
    return self::common(function($v) {return $v['key'];});
  }

  public static function newList2()
  {
    return self::common(function($v) {return $v;});
  }

  private static function common(callable $callback)
  {
    $returnList = [];
    foreach(self::SOME_LIST as $v) {
      $returnList[] = $callback($v);
    }
    return $returnList;
  }
}

var_dump(SomeForeach2::newList());
var_dump(SomeForeach2::newList2());
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?