使用数组帮助函数实现不限顺序填写参数

一般情况下,我们在类中定义函数时经常需要向函数传递参数

 1 <?php
 2 
 3     class  image{
 4 
 5          private $name;
 6          private $age;
 7          private $adress;
 8 
 9          function  getinfo($name,$age,$adress){
10 
11                 $this->name = $name;
12                 $this->age = $age;
13                 $this->adress = $adress;
14          }
15 
16     }                    

在使用函数的过程中,我们对于参数的录入需要严格的按照其顺序,并且不能漏掉某个参数,

尽管在参数设置了默认值的情况下依然要给它留出位置。

在学习高洛峰老师的细说php中,高老师讲到了关于利用数组实现自由式的参数录入形式,

下面介绍下实现步骤:

首先在定义函数时,把所有的参数放到数组中:

public function getinfo(  $options = array() ){


}

然后需要在函数内容把数组中的参数赋值给类的属性值

而在调用方法时:

 getinfo( $arr = array( 'name'=>'timor','age'=>12,'adress'='yudel') ){
        
    }

在定义函数时要把函数接收到的参数赋值给类的属性:

也就是说该函数使用的参数必须是类中的属性或者脚本中定义的变量

在类中:

 1     public function getinfo(  $options = array() ){
 2 
 3             foreach ($options as $key => $val) {                   //取出数组中的参数
 4                 if (!in_array($key, get_class_vars(get_class($this)))) {     //判断参数和类中的属性是否相同
 5                     continue;
 6                 }else{
 7                     $this->$key = $val;                        //把参数的值赋给类中的属性
 8                 }
 9             }
10     }

这样之后,当我们需要调用getinfo()时,可以写成下面的形式:

 1 getinfo( $arr = array( 'name' => 'timor' , 'age' => 12)){
 2 
 3 }
 4 
 5 //也可以打乱参数的顺序
 6 
 7 getinfo( $arr = array(  'age' => 12, 'name' => 'timor' )){
 8 
 9 }
10 
11 //也可以漏掉某个参数不写
12 
13 getinfo( $arr = array( 'name' => 'timor' )){
14 
15 }

不知道这样子是不是有点绕了...

在我看来这种做法确实可以实现灵活的调用函数,不过我似乎也不怎么看好这种方法。

里面又调用了很多方法,这些都会额外的占用一些内存,并且好像这么做的话还会给人一种错乱的感觉,

把参数封装到数组里面,似乎有复杂化了对参数的定义...

以后看实用性吧...

 

posted @ 2015-05-17 17:55  timor去开路  阅读(80)  评论(0编辑  收藏  举报