我正在尝试使用一个确定薪水和有薪水的人数的类,OOP 对我来说是新的,我已经浏览了大量的教程和示例,但我不确定我是否在以下方面使用最佳实践:
class quickCalc
{
private $salary = 0;
private $person = 0;
private $person_salary = 0;
private animal = 0;
private animal_salary = 0;
public function addCost($type, $salary)
{
$this->$type++;
$type_two = $type.'_salary';
$this->$type_two += $salary;
}
public function getCount($type)
{
return $this->$type;
}
public function getCost($type)
{
$type = $type.'_salary';
return $this->$type;
}
}
$test = new quickCalc();
$test->addCost('person', 15000);
echo $test->getCount('person'); //1
echo $test->getCost('person'); //10000
echo $test->getCount('animal'); //0
可以看出,当我添加一个人或动物等时,相关属性增加 1,并且工资值添加到现有值中
我不确定的是,是否最佳做法是通过对象传递属性名称,如下所示:
public function addCost($type, $salary)
{
$this->$type++;
}
或者每个属性都应该有自己的函数,例如:
public function addPerson($salary)
{
$this->person++;
$this->person_salary++;
}
每个属性都应该有自己的函数。拥有这样的"动态"属性感觉很奇怪。
但是,您可以在 php 中检查属性重载的工作原理。例子很有趣。
我必须补充一点,在我看来,您的任务应该涉及一个数组(或迭代器)。您可以使用现有方法添加工资,然后计算或计算平均值等。
另一种解决方案是,不是让单独的private
属性使用数组来存储单个类型和相应的工资值。下面是一个示例:
class quickCalc{
private $type = array('person' => 0, 'animal' => 0);
private $salary = array('person' => 0, 'animal' => 0);
public function addCost($type, $salary){
$this->type[$type]++;
$this->salary[$type] += $salary;
}
public function getCount($type){
return $this->type[$type];
}
public function getCost($type){
return $this->salary[$type];
}
}
$test = new quickCalc();
$test->addCost('person', 15000);
echo $test->getCount('person') . "<br />"; // 1
echo $test->getCost('person') . "<br />"; // 15000
$test->addCost('animal', 20000);
$test->addCost('animal', 20000);
echo $test->getCount('animal') . "<br />"; // 2
echo $test->getCost('animal') . "<br />"; // 40000
输出:
1
15000
2
40000