批改状态:合格
老师批语:
<?php// 声明一个类文件: 声明的类与这个类所在的文件推荐同名// 类: 对象的模板class Dsij{//protected: 受保护成员,仅限本类以及子类访问protected $name;protected $digit;// 类实例化的时候会调用它, 构造方法public function __construct($name,$digit){//$this: 当前类实例的引用$this->name = $name;$this->digit = $digit;}// 实例方法public function show():string{return "$this->name : $this->digit 元";}}
<?php// 类必须实例之后才可以访问内部的实例成员// 加载类文件require 'zuoye.php';// new : 类实例化$lslh = new Dsij('小米电视', 7899);echo $lslh->show(),'<br>';

// 类的静态成员class Ldjtdy{// 静态属性protected static $name;private static $price;// 构造方法public function __construct($name, $price){// 静态成员与实例无关,当然不能用$this访问,用类的引用// self: 当前类的引用self::$name = $name;self::$price = $price;}// 静态方法public static function show(){// 静态方法中不能用$thisreturn sprintf('商品信息: %s<br> 商品价格: %d', self::$name, self::$price);}}$Ldjtdy = new Ldjtdy('电脑', 12345);echo Ldjtdy::show(), '<hr>';// 子类, 类的复用 extends: 扩展class zlfy extends Ldjtdy{// 属性扩展private static $orcdf;// 重写父类构造器public function __construct($name, $price, $orcdf){parent::__construct($name, $price);self::$orcdf = $orcdf;}// 重写父类普通方法public static function show(): string{return parent::show() . "<br>数量:" . self::$orcdf;}}$orcdf = new zlfy('小米电视', 12998, 123);echo zlfy::show(), '<hr>';

trait: 理解为一个公共方法集; trait 借用了class语法实现的一个轻量级的"类",但不是类,所以不能"实例化"在要使用trait的类中,使用use关键字引用它即可,当一个类引入多个trait时,很容易发生trait成员的命名冲突当trait中存在与父类同名的成员时,trait优先,own > trait > parent
<?phptrait Jtxq{public function h1(){return 'Hello 你好呀';}}// 在要使用trait的类中,使用use关键字引用它即可class A{use Jtxq;}echo (new A)->h1(),'<hr>';// trait的冲突与优先级的解决方案trait A01{public function asxm(){return '不早了该写作业了!';}}trait A02{public function asxm(){return ' 请打开网站 : php.cn';}}class G{use A01,A02{// 1.优先级A01::asxm insteadOf A02;// 2.别名A02::asxm as qasxhm;}}echo (new G)->asxm(),(new G)->qasxhm(),'<hr>';

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号