Correction status:qualified
Teacher's comments:
在php中类的使用很频繁,下面我来介绍下类中的基本的属性和方法使用.
以下是我的代码.
<?php echo "<h2>类的申明与实例化</h2>"; class test1 { public function hello(){ return "我是一个类"; } } $test= new test1(); echo $test->hello(),"<br>"; $test->hello1 = function (){ return "我是另外一个类"; }; echo call_user_func($test->hello1); echo "<hr>"; echo "<h2>类常量与类的属性重载</h2>"; class test2{ //使用const的关键字来创建类常量,使用大写来定义常量的名称 const TEST = "我是一个测试2"; //创建三个私有属性 private $name; private $age; private $salary; public function __construct($name,$age,$salary)//使用构造方法对三个私有属性进行初始化 { $this->name = $name; $this->age = $age; $this->salary = $salary; } //设置获取器使得属性重载可以访问私有的条件,还可以设置条件进行访问的限制 public function __get($name) { if ($name == 'salary'){ exit( "你无权查看"); }else{ return $this->$name; } } //设置设置器使得属性修改访问私有条件的属性, public function __set($name, $value) { if ($name == 'salary'){ exit( "你无权修改"); }else{ return $this->$name = $value; } } //设定属性查询规则 public function __isset($name) { if ($name == 'salary'){ return false; } return isset($this->$name); } //设定属性销毁方法 public function __unset($name) { if ($name == 'salary' || $name == "name"){ return false; } unset($this->$name); } } //使用类的名称加双冒号访问类中的常量 echo test2::TEST,"<br>"; $test2 = new test2('test','25','6000'); echo $test2->name,"<br>"; echo $test2->age,"<br>"; //$test2->salary = 5000; $test2->name = "小王"; echo $test2->name,"<br>"; echo isset($test2->salary) ? "有<br>" : "没有<br>"; echo isset($test2->name) ? "有<br>" : "没有<br>"; unset($test2->name); echo $test2->name,"<br>"; unset($test2->age); echo $test2->age,"<br>"; echo "<hr>"; echo "<h2>类的继承与方法的重写</h2>"; //创建一个父类 class test3 { public $name; protected $age; const TEST_1 = "我是父类的常量"; public function __construct($name,$age) { $this->name =$name; $this->age =$age; } } //创建一个子类继承父类属性和方法 class test3_1 extends test3 { private $salary; public function __construct($name, $age,$salary) { parent::__construct($name, $age);//引用父类的构造方法进行重写 $this->salary = $salary; } public function __get($name) { return $this->$name; } public function __isset($name) { if ($name == "salary"){ return false; } return isset($this->$name); } } $test3_1 = new test3_1("小明",20,5000); echo test3_1::TEST_1; echo $test3_1->name,"<br>"; echo $test3_1->age,"<br>"; echo $test3_1->salary,"<br>"; echo isset($test3_1->salary) ? "有<br>":"没有<br>"; echo isset($test3_1->name) ? "有<br>":"没有<br>"; echo "<hr>"; echo "<h2>类中静态成员的声明和访问</h2>"; class test4{ //静态类的关键字是static,在3p后面紧跟着. public static $name = "小红"; public static $age="28"; public static $salary="6000"; } echo test4::$name,"<br>"; echo test4::$age,"<br>"; echo test4::$salary,"<br>";
点击 "运行实例" 按钮查看在线实例