批改状态:未批改
老师批语:
<?php
header("content-type:text/html;charset=utf-8");
/*1.类声明与实例化*/
class Fruit
{
public $name = '苹果';//访问不受限属性
public $price = '20';//访问不受限属性
protected $discount = 0.8;//受保护的属性,只可以在本类中使用或者子类中应用
private $supplier = '红富士';//私有属性,只可以在自己类中使用,子类也不可以访问
public function show_price(){
return $this->name.'的价格:'.$this->price;
}
public function getSupplier(){
return $this->supplier;
}
}
$fruit = new Fruit;
echo $fruit->name,'<br>';
echo $fruit->show_price(),'<br>';
//echo $fruit->discount;//会报错提示受保护属性外部不可访问
//echo $fruit->supplier;//会报错提示私有属性外部不可访问,
//当类中属性私有化之后外部访问时类中必须提供访问接口
echo $fruit->getSupplier(),'<br>';
/*2.类常量与类属性的重载*/
class ArticleRelease{
//设置类的属性私有,是为了对外部对类中属性访问进行限制
private $author;//作家笔名
private $pay;//作家酬劳
private $numberOfArticles;//作家目前在本网站发布文章数量
const WEB = 'www.articl.com'; //类常量
//构造方法__contract,当实例化类时,自动调用的方法
public function __construct($author,$pay,$numbersOfArticles) {
$this->author = $author;
$this->pay = $pay;
$this->numberOfArticles=$numbersOfArticles;
}
//获取类属性,当类中属性私有之后外部访问不到,
//可以用__get($name)提供接口访问,此方法属于魔术方法自调用
public function __get($name){
return $this->$name;
}
//设置属性的值,当属性私有之后外部不允许访问,没办法改变属性的值,因此要用到__set($name,$value)
//魔术方法,自动调用
public function __set($name,$value){//设置类属性
if('numberOfArticles'==$name) return false;//不允许外部改变当前numberOfArticles的值
$this->$name = $value;
}
public function __isset($name){//检测类属性是否存在
if('pay'==$name) return false;//不允许外部检测pay的值
return isset($this->$name);
}
public function __unset($name){//销毁类属性
if($this->author == $name) return false;
unset($this->$name);
}
}
//访问类常量
echo ArticleRelease::WEB;
echo '<br>';
$ArticleRelease = new ArticleRelease('黎明莫伊','8000','3522');
echo $ArticleRelease->author;
$ArticleRelease->numberOfArticles = '2200';
echo $ArticleRelease->numberOfArticles;
echo isset($ArticleRelease->pay)?'存在':'不存在';//结果不存在,类中有但是限制检测
echo isset($ArticleRelease->numberOfArticles)?'存在':'不存在';//结果存在,类中有且没有限制检测
/*3.类的继承与方法重回*/
class One{
protected $a = 10;
protected $b = 20;
public $m = 10000;
const LANGUAGE = 'english';
public function add(){
$c= $this->a + $this->b ;
return $c;
}
public function show(){
return $this->m;
}
}
class Two extends One{
public function add(){
return $this->m;//当前类中无$m属性,此时引用父类中的$m
}
}
$p1 = new One;
$p2 = new Two;
echo '<br>';
echo $p1->add();//输出30
echo '<br>';
echo $p2->add();//输出值已经与父类不一样
echo '<br>';
echo $p2->show();//引用父类的属性
echo '<br>';
/*类中静态成员*/
class Three{
public static $a = 222;
public static $b = 20;
public static $m = 10000;
const LANGUAGE = 'english';
public static function add(){//类中静态方法的引用自身属性不允许使用$this,用self::$a;
return self::$a + self::$b ;
}
public static function show(){
return $this->m;
}
}
echo Three::$a;//访问类中静态变量
echo '<br>';
echo Three::add();//访问类中静态方法
echo '<br>';
echo Three::LANGUAGE;//访问类中常量
?>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号