嗯,这里有一些事情要做,但您知道您需要$age 和$color 属性,以及读取这些属性的方法。不过,您可能不想编写它们。
所以,我可能会:
getAge(){ return $this->age; }
getColor(){ return $this->color; }
现在,您想随机分配颜色和年龄,这意味着您需要 rand 函数(那里还有其他选项,但 rand 会很好)。现在,如果我要这样做,我会在构造函数中放入类似的内容:
// assuming we're testing for male or female
// you really should look into why this works.
$this->gender = ( rand( 0, 1 ) )? self::MALE: self::FEMALE;
// notice the self::MALE and self::FEMALE? Those are class constants.
// http://php.net/manual/en/language.oop5.constants.php
// if you want to get this question *right* you'll need to look at those
您的机器实际上非常简单。他们只测试每只羊的年龄是否足以被剪毛,然后在此基础上增加一个计数器。
// assuming they are looking for a count of female sheep
// and state variables 'male' and 'female' which are initialized at 0
function processSheep( $sheep )
{
foreach( $sheep as $test )// stupid self-pluralizing nouns.
{
if( $sheep->getGender() == Sheep::MALE ) $this->males++;
else $this->females++; // obviously, you're going to need to swap
// out one of these increments for an echo.
}
}
function getNumberOfMales(){ return $this->males; }
用两台机器,计算男性数量:
$mach1->getNumberOfMales() + $mach2->getNumberOfMales();
有n台机器的数组,男性的数量:
$males = 0;
foreach( $machs as $mach ){ $males += $mach->getNumberOfMales(); }