使用PHP的数组函数优化Value对象


Value Object optimization using array functions of PHP

我在Value Object中有这两个方法:

public final function unlockableLetters()
{
    return [
        [],
        ['A', 'B'],
        ['C']
    ][$this->level];
}
public final function unlockedLetters()
{
    return [
        [],
        ['A', 'B'],
        ['A', 'B', 'C'],
    ][$this->level];
}

第一个返回每个级别的可解锁元素。

  • 在级别0,返回[]
  • 在级别1,返回A和B
  • 在级别2返回C

第二个返回未锁定的元素。

  • 在级别0,返回[]
  • 在级别1返回A和B。//NULL+A+B
  • 在级别2返回A、B和C。//A+B+C

有一种方法可以使用php的数组函数来创建unlockLetters()从索引0到当前$this->级别返回的数组的合并?

编辑我只想在unlockableLetters()方法中留下字母。所以,unlockedLetters()可以从第一个方法"构建"自己的返回值。如果前者发生变化,后者就会发生变化。

您想要什么还不完全清楚。正如我在评论中所说:

同意@deceze的观点,不清楚你想合并什么。。。你是说你想使用数组函数而不是硬编码从unlockLetters()生成unlockedLetters()的返回吗?此外,我认为更好的方法名称在这里是有序的,因为这也会让它变得混乱。。。我会使用getUnlockableLettersgetUnlockedLetters()或类似的东西,这取决于它们的使用方式。

然而,我认为你的意思可能看起来像这样:

// add a property so we can reference it - you might want to adjust
// the visibility to private or public depending on its nature
protected $unlockableLetters = [
    [],
    ['A', 'B'],
    ['C']
];
public final function unlockLetters()
{
    // just return the reference to the letters for the level
    return $this->unlockableLetters[$this->level];
}
public final function unlockedLetters()
{
    // slice off the array of latters from the lowest level 
    // to the current one - note the +1 since array_slice
    // wants a length and our offsets are 0-based and thus length-1
    $data = array_slice($this->unlockableLetters, 0, $this->level+1);
    // use array reduce to build a single array that has
    // all the letters for levels 0 --> $this->level
    return array_reduce($data, function ($merged, $datum) {
       return array_merge($merged, $datum);
    }, []);
}

只要我理解你的问题,你就在寻找这个

public final function unlockableLetters() {
    $unlockables = [
        [],
        ['A', 'B'],
        ['C']
    ];
    return array_reduce(array_slice($unlockables, 0, $this->level + 1), function($carry, $item){
        return array_merge($carry, $item);
    }, []);
}

我同意这里的其他开发人员的看法。问题不清楚。但我的猜测是:

public final function unlockLetters()
{
    $arr =  [
        [],
        ['A', 'B'],
        ['C']
        ];
    return $arr[$this->level];
}
public final function unlockedLetters()
{
    $arr = [
        [],
        ['A', 'B'],
        ['A', 'B', 'C']
    ];
    return $arr[$this->level];
}