array_walk()

为啥使用?

函数应该只做一件事

这是迄今为止软件工程里最重要的一个规则。当函数做超过一件事的时候,他们就难于实现、测试和理解。当你隔离函数只剩一个功能时,他们就容易被重构,然后你的代码读起来就更清晰。如果你光遵循这条规则,你就领先于大多数开发者了。

Bad:

function emailClients($clients) {
  foreach ($clients as $client) {
    $clientRecord = $db->find($client);
    if($clientRecord->isActive()) {
       email($client);
    }
  }
}

Good:

function emailClients($clients) {
  $activeClients = activeClients($clients);
  array_walk($activeClients, 'email');
}

function activeClients($clients) {
  return array_filter($clients, 'isClientActive');
}

function isClientActive($client) {
  $clientRecord = $db->find($client);
  return $clientRecord->isActive();
}

基本使用

<?php
function myfunction($value,$key)
{
echo "The key $key has the value $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction");
?>

具体使用demo

<?php

class demo1
{
    public function index()
    {
        $a = array("a" => "red", "b" => "green", "c" => "blue");

        array_walk($a, array(new demo2(), 'myfunction'), ['username'=>'liaosp']);

        var_dump($a);
    }
}

class demo2
{
    /**
     * @param $value
     * @param $key
     * @param array $userdata
     * @var  $username
     */
    public function myfunction(&$value, $key, array $userdata)
    {
        $username ='';//来源userdata 数组
        extract($userdata);
        $value = $username;
    }
}

//so good !!! demo3

class demo3{
    public function emailClients($clients) {
        $activeClients = $this->activeClients($clients);
        array_walk($activeClients, array($this,'email'));
    }

    function activeClients($clients) {
        return array_filter($clients, array($this,'isClientActive'));
    }

    public function isClientActive(array $client) {
        $status = 0;//extract 赋值
        extract($client);
        if($status ==0){
            return false;
        }
        return true;
    }
    public function email($value){
        var_dump($value);
    }

}

//$obj = new demo1();
//$obj->index();

$obj = new demo3();
$client = [
    ['username'=>'liaosp','status'=>1,'email'=>'liaosp@qq.com'],
    ['username'=>'mm','status'=>1,'email'=>'mm@qq.com'],
];
$obj->emailClients($client);


posted @ 2019-09-04 15:58  liaosp  阅读(112)  评论(0编辑  收藏  举报