(1)对于php的默认值的使用和C++有点类似,都是在函数的输入中填写默认值,以下是php方法中对于默认值的应用:
<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return " </br> Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot"); function makeyogurt($flavour, $type = "acidophilus")
{
return "</br>Making a bowl of $type $flavour.\n";
}
echo makeyogurt("raspberry"); ?>
以上程序的输出为:
当输入为空时,当前的值采用默认的值,当不为空时,采用输入值;
(2)以下是PHP中对于class中默认值的使用:
<?php class pot{ protected $x;
protected $y;
protected $c;
public function __construct($x = 0, $y=1){ $this->x = $x;
$this->y = $y;
$this->c = $this->x+$this->y;
} function printC()
{
echo "</br>".$this->c;
}
} $pot1 = new pot(9, 6);
$pot1->printC();
$pot2 = new pot();
$pot2->printC(); ?>
输出结果为:
(三)继承取默认值:
(1)当继承的class有construct的情况:
<?php
class pot{ protected $x;
protected $y;
protected $c;
public function __construct($x = 0, $y=1){ $this->x = $x;
$this->y = $y; $this->c = $this->x+$this->y;
} function printC()
{
echo "</br>".$this->c;
}
} class pots extends pot{
protected $x;
protected $y;
protected $c;
public function __construct($x = 10, $y = 20){ $this->x = $x;
$this->y = $y;
$this->c = $this->x+$this->y;
}
}
$pots1 = new pots(10, 5);
$pots1->printC();
$pots2 = new pots();
$pots2->printC(); ?>
当继承的class有自己的construct,那它的取值为自身的construct的取值, 对于自身的construct没有默认值,则默认取0值, 对于自身没有的方法,继承父类的方法;
以上的输出结果为:
(2)当继承的class没有construct的情况,取父类的值:
<?php
class pot{ protected $x;
protected $y;
protected $c;
public function __construct($x = 0, $y=1){ $this->x = $x;
$this->y = $y; $this->c = $this->x+$this->y;
} function printC()
{
echo "</br>".$this->c;
}
} class pots extends pot{ }
$pots1 = new pots(10, 5);
$pots1->printC();
$pots2 = new pots();
$pots2->printC(); ?>
以上输出结果为: