【问题标题】:how to instantiate an object even if not all parameters are passed to the constructor即使不是所有参数都传递给构造函数,如何实例化对象
【发布时间】:2020-05-03 05:05:15
【问题描述】:

我试图让创建对象的实例成为可能,即使我输入了两个参数中的一个。

这就是我所做的:

class BMW implements iCars
{
  private $_price;
  private $_weight;

  function __construct($price, $weight)
  {
    $this->_price = $price;
    $this->_weight = $weight;

    if ($weight === null) {
        $weight = "4242";
    }
  }

  function setPrice()
  {
    return $this->_price;
  }
  function setWeight()
  {
    return $this->_weight;
  }
  function getPrice()
  {
    return $this->_price;
  }
  function getWeight()
  {
    return $this->_weight;
  }
}

如果我将重量和价格放入参数中,或者只是价格,我需要能够创建一个实例。

【问题讨论】:

标签: php class oop object constructor


【解决方案1】:

您可以在实例化对象时添加null for 参数,例如:

$car = new BMW(123, null);

演示:http://sandbox.onlinephpfunctions.com/code/46cd960eff0530c0d0a3a384fe426cae4022523f

或者您可以更改构造函数定义以使第二个参数可选(通过使用default parameter arguments):

function __construct($price, $weight = null)
{
    $this->_price = $price;
    $this->_weight = $weight;
    //...
}

//....

$car = new BMW(123);

演示:http://sandbox.onlinephpfunctions.com/code/27970a41be1ff259d112a8a1a5db0d25c940092d


注意额外说明:我怀疑

$weight = "4242";

构造函数中的if 语句可能不是您想要的——它只会设置传入的$weight 变量,当构造函数完成时该变量将丢失。我想你真的打算在对象上设置属性,例如

$this->_weight = 4242;

(注意我也去掉了引号,因为它是一个数字,而不是一个字符串。)

【讨论】:

  • 感谢 ADyson,您的额外说明:如果参数中没有传递权重,我只想将“4242”分配给权重属性
【解决方案2】:

尝试将您的构造函数更改为:

function __construct($price, $weight = null)
{
    $this->_price = $price;
    $this->_weight = $weight;



    if ($weight === null) {
        $weight = "4242";
    }
}

在参数处添加= null,如果不传递值,会将它们设置为默认值。

所以$car = new BMW(25000); 可以正常工作。

编辑:如果您总是希望 4242 作为默认值,您可以在构造函数签名中添加它。

function __construct($price, $weight = "4242")
{...}

$car = new BMW(123);
echo $car->getWeight();
//Will echo 4242

您将不再需要if ($weight == null)

【讨论】:

  • @ADyson 你是对的。 $weight = null 在构造函数的签名中是正确的。谢谢
  • 为什么不干脆__construct($price, $weight = "4242")
  • @GiacomoM 刚刚更新了它;)我也想到了,好点谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多