PHP设置可选参数

时间:2015-03-27 07:12:16

标签: php

class JSON_Response{
            private $ResponseCode = "RVN-775";
            private $ResponseDescription = "Unknown Request";
            private $ResponseOf = "Unknown";
            private $ResponsePayload = array("PayloadEmpty"->"Yes");

            function __construct(
                            $ResponseCode = null,
                            $ResponseDescription = null,
                            $ResponseOf = null,
                            $ResponsePayload = null,
                            )
        {
            $this->ResponseCode = $ResponseCode ? $ResponseCode : $this->ResponseCode;
            $this->ResponseDescription = $ResponseDescription ? $ResponseDescription : $this->ResponseDescription;
            $this->ResponseOf = $ResponseOf ? $ResponseOf : $this->ResponseOf;
            $this->ResponsePayload = $ResponsePayload ? $ResponsePayload : $this->ResponsePayload;

        }
    }

有没有更好的方法来写这个?

如果构造函数在创建对象时获取参数,我希望设置类变量,如果没有给出参数,那么我希望类变量是默认值。

3 个答案:

答案 0 :(得分:1)

如果传递了一些参数,这将覆盖默认值:

class JSON_Response{
      function __construct(
                        $ResponseCode = "RVN-775",
                        $ResponseDescription = "Unknown Request",
                        $ResponseOf = "Unknown",
                        $ResponsePayload =  array("PayloadEmpty"->"Yes"),
                        )
    {
        $this->ResponseCode = $ResponseCode;
        $this->ResponseDescription = $ResponseDescription;
        $this->ResponseOf = $ResponseOf;
        $this->ResponsePayload = $ResponsePayload;

    }
}

答案 1 :(得分:0)

你可以尝试传递数组:

function __construct($args) { 
   foreach ($args as $k => $v) {
       //if (property_exists($this,$k)) -- optionally you want to set only defined properties
       $this->{$k} = $v;
   }
}

然后使用:

创建对象
$object = new JSON_Response(array(
    'ResponseOf' => 'test'
));

答案 2 :(得分:0)

如果params数组存在类变量键,则可以在数组中使用所有__constructor()并在类变量中赋值,这会减少代码大小并更好地使用它,请参阅下面的示例代码

<?php

class JSON_Response {

    private $ResponseCode = "RVN-775";
    private $ResponseDescription = "Unknown Request";
    private $ResponseOf = "Unknown";
    private $ResponsePayload = array("PayloadEmpty" => "Yes");

    function __construct($params = array()) {
        if(!empty($params)){
            foreach ($params as $k => $v){
                $this->{$k} = $v;
            }
        }
    }
}

#call class from with array params
$class_params = array('ResponseCode' => '', 'ResponseDescription' => '',
 'ResponseOf' => '', 'ResponsePayload' => '');
$obj = new JSON_Response($class_params);

如果params键中不存在任何类变量,则类变量默认值将使用