如果我们有这么一个类:
class User{
public $name;
public $password;
public function setName($name){
$this->name=$name;
print_r("my name is $name");
}
public function setPassword($password){
$this->password=$password;
print_r("my password is $password");
}
}
有这么一个列表的需要去调用:
$dataList=[
["name"="a1","password"="a1"],
["name"="a2","password"="a2"],
["name"="a3","password"="a3"],
.......
["name"="aN","password"="aN"]
]
一开始我们调用类的方法和属性的时候,我们也许会选择这么调用:
$this->setName($name);
$this->setPassword($password);
$this->name;
$this->password;
这里只有两个属性值需要set,但是如果有二十个呢?是不是要一个一个的写$this->setAttr1(),$this->setAttr2()........? 这无疑是一个繁杂的操作。试想,如果我们有大量的属性和方法需要调用,那么我们这样做是不是太耗时耗力了?分分钟就不想写了有木有。
其实我们还有另一种简便的写法,如下:
<?php
for(i=0;i<=N;i++){
array_walk($dataList[i],function($value,$key){
$method=“set”.ucfirst($key);
$attribute=$key;
$this->$method($value);
$this->$attribute;
})
}
?>
example:
$dataList=["a"=>"red","b"=>"blue","c"=>"black"];
public function setTest( $data = ["a"=>"red","b"=>"blue","c"=>"black"])
{ array_walk($data, function ($value, $key) { $method = "test" . $key;//构建方法名 $attribute=$key;//如果属性名有特殊要求可以单独的构建 $this->$method($attribute,$value); }); } protected function testa($attr,$value) { print_r("This is testa method;The '$attr' attribute value is " . $value . "<br>"); } protected function testb($attr,$value) { print_r("This is testb method;The '$attr' attribute value is " . $value . "<br>"); } protected function testc($attr,$value) { print_r("This is testc method;The '$attr' attribute value is " . $value . "<br>"); }
/**********************/
print:
This is testa method;The 'a' attribute value is red
This is testb method;The 'b' attribute value is blue
This is testc method;The 'c' attribute value is black