私信  •  关注

Erick

Erick 最近创建的主题
Erick 最近回复了
11 年前
回复了 Erick 创建的主题 » php python样式的函数变量[重复]

通常不能,但我认为有很多方法可以将命名参数传递给php函数。就我个人而言,我使用数组来传递定义,然后调用需要传递的内容:

class Test{
    public $a  = false;
    private $b = false;
    public $c  = false;
    public $d  = false;
    public $e  = false;
    public function _factory(){
        $args    = func_get_args();
        $args    = $args[0];
        $this->a = array_key_exists("a",$args) ? $args["a"] : 0;
        $this->b = array_key_exists("b",$args) ? $args["b"] : 0;
        $this->c = array_key_exists("c",$args) ? $args["c"] : 0;
        $this->d = array_key_exists("d",$args) ? $args["d"] : 0;
        $this->e = array_key_exists("e",$args) ? $args["e"] : 0;
    }
    public function show(){
        var_dump($this);
    }
}


$test = new Test();
$args["c"]=999;
$test->_factory($args);
$test->show();

这里有一个实例: http://sandbox.onlinephpfunctions.com/code/d7f27c6e504737482d396cbd6cdf1cc118e8c1ff

如果我必须传递10个参数,其中3个是我真正需要的数据,那么传递到函数中是不明智的,比如

return myfunction(false,false,10,false,false,"date",false,false,false,"desc");

使用我给出的方法,可以将10个参数中的任意一个设置为数组:

$arr['count']=10;
$arr['type']="date";
$arr['order']="desc";
return myfunction($arr);

我在我的博客上有一篇文章更详细地解释了这个过程。

http://www.tbogard.com/2013/03/07/passing-named-arguments-to-a-function-in-php