PHP学习(15)面向对象开发学习(5)

本文深入探讨了PHP中类的定义与使用,包括final关键字防止类或方法被继承或重载,static用于声明静态属性并通过self访问,以及通过const声明不可变常量等关键概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么函数都没加时
<?php

class MyPc{
public $name='my computer';
function power(){//final当定义类的时候该类将不能被继承
echo $this->name.",the computer is opening...";
}

}

class My extends MyPc{//extends重载

function power(){
echo "********";//继承时覆盖同名之前类
echo MyPc::power()."********";//继承时不会覆盖同名之前类,加到之前类后输出
}
}

$p=new My();

$p->power();


?>



final(锁定)
<?php

final class MyPc{//final(锁定)当定义类的时候该类将不能被重载
public $name='my computer';
final function power(){//final(锁定)当定义方法的时候该方法将不能被重载
echo $this->name.",the computer is opening...";
}

}

$p=new MyPc();

$p->power();


?>



static静态属性,self访问静态属性
<?php

class MyPc{
static $name='my computer';//无法被访问
static function power(){
//静态属性需要用self来访问
echo self::$name.",the computer is opening...";
}

}


//$p=new MyPc();

//$p->power();



echo MyPc::$name="你的diannao";//可以访问,静态属性已经在内存之中,不用实例化,可以修改
echo MyPc::power();



?>

const只能修饰类当中的成员属性!建议大写常量常量,不使用$符号。
<?php

final class MyPc{
const NAME='my computer';
static function power(){
//静态属性需要用self来访问
echo self::NAME.",the computer is opening...";
}

}


$p=new MyPc();

$p->power();



?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值