PHP 设置可选参数


PHP setting optional arguments

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;
        }
    }

有没有更好的写法?

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

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

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;
    }
}
你可以

尝试传递一个数组:

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'
));

您可以使用数组中的所有__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);

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