php 花式批量调用方法与属性

如果我们有这么一个类:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值