批改状态:合格
老师批语:是单例模式, 在多次页面级访问时共享有且唯一一个对象实例.
class Player{//成员属性一定要有范围访问修饰符 public protected private staticpublic $name;//抽象属性没有赋值public $name="Jordan";public $height;public $team;protected $PlayerNum;private $weight;public function __construct($name,$height,$team,$weight){//初始化类成员,让类实例化的状态稳定下来//步骤1:自动生成一个类实例$obj=new Player;// 步骤2对对象的属性进行初始化赋值$this->name=$name;//$this代表本对象,作用是完成内部成员的访问$this->height=$height;$this->team=$team;$this->weight=$weight;//步骤3:返回对象 return $obj;}//成员实例方法public function jog(){echo "$this->name is jogging,his weight is $this->weight <br/>";}public function shoot(){echo "$this->name is shooting,his height is $this->height <br/>";}}$npl=new Player;//调用(对象引用->属性名称)echo $npl->name;echo '<hr/>';//对象属性赋值$npl->height='198cm';echo $npl->height;echo '<hr/>';//对象方法的访问echo $npl->jog();
class User{public static $name="胡歌";protected $_config=['auth-on'=>'true','auth-type'=>1,//1代表实施认证,2代表登录认证];public static $nation="China";private static $salary;static $count;public function __construct($name,$salary){//访问静态成员::self(独有方法)self::$salary=$salary;self::$name=$name;self::$count++;}public static function getCount(){return sprintf("User类被实例化了%d次<br/>",self::$count);}}//对类中的静态成员属性进行赋值User::$count=0;//实例化类$user=new User("张三","20000");//通过对象的引用访问静态成员echo $user->getCount();//同上一样效果echo User::getCount();echo User::$name;//张三
//在静态成员方法中访问非静态成员属性 protected $_configpublic function getConfig(){return printf('认证开关:%s<br/>,认证类型%d<br/>',$this->_config['auth-on'],$this->_config['auth-type']);}//调用非静态成员echo $user->getConfig();###类的继承```php//类的继承class son extends Product{//属性扩展private $num;//重写父类的构造器public function __construct($name,$price,$num){//parent关键字,调用父类的成员方法parent::__construct($name,$price);$this->num=$num;}//重写父类的普通方法public function show():string{return parent::show().",数量$this->$num 个";}public function total(){return "$this->name,总计:".($this->price*$this->num)."元";}}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号