gpt4 book ai didi

php - 如何为对象创建默认值? PHP

转载 作者:行者123 更新时间:2023-12-04 21:19:53 25 4
gpt4 key购买 nike

假设我有一个 Human 类,它的变量 $gender 没有分配任何值。 Human 有一个带有年龄、性别、高度和体重参数的构造函数。

我有另一个名为 Female 的类,它继承自 Human,但现在 Female 类正在用字符串 Female 覆盖 $gender 变量。

当我创建对象时,假设 $f = new Female(12, 'female', 123, 40);如何在创建对象时跳过输入女性?

我认为我们需要在 Female 类中创建另一个新的构造函数,我在 Female 类构造函数的参数中有 age, gender = 'female', height and weight 但这不是似乎有效。

我尝试在创建对象时将性别部分留空或尝试输入空字符串,例如 ""

有人可以帮我一下吗?非常感谢。

人类类代码

class Human {
protected $age = 0;
protected $gender;
protected $height_in_cm;
protected $weight_in_kg;

function __construct($age, $gender, $heightCM, $weightKG)
{
$this->age = $age;
$this->gender = $gender;
$this->height_in_cm = $heightCM;
$this->weight_in_kg = $weightKG;
}

/**
* @return int
*/
public function getAge()
{
return $this->age;
}

/**
* @return string
*/
public function getGender()
{
return $this->gender;
}
}

女性类代码

require_once('Human.php');
class Female extends Human{
protected $gender = 'female';

function __construct($age, $gender = 'female', $heightCM, $weightKG)
{
$this->age = $age;
$this->gender = $gender;
$this->height_in_cm = $heightCM;
$this->weight_in_kg = $weightKG;
}
}

$f = new Female(12,'female',123,40);
echo "Your gender is ". $f->getGender()."<br>";

最佳答案

简单地覆盖构造函数:

class Human {
public function __construct($age, $gender, $height, $weight) {
}
}

class Female extends Human {
public function __construct($age, $height, $weight) {
parent::__construct($age, 'Female', $height, $weight);
}
}

关于php - 如何为对象创建默认值? PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31093947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com