php基础--取默认值以及类的继承

本文介绍了PHP中函数参数和类构造函数默认值的使用方法。包括基本的函数参数默认值设置、类构造函数默认值设置及类继承时默认值的处理方式。

(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();

?>

以上输出结果为:

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值