Blogger Information
Blog 65
fans 2
comment 0
visits 60409
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
通熟易懂的PHP案例,搞会OOP中这3个关键字,明天找‘对象’不再难...
张福根一修品牌运营
Original
671 people have browsed it

OOP:final, self, $this举例使用

案例效果:

OOP案例

案例源码:

一、$this关键字:

  1. <?php
  2. // 特殊的对象引用$this,代表本对象,专门完成对象内部成员的访问
  3. class people{
  4. public $name;
  5. public $age;
  6. public $height;
  7. public function __construct($name = "" , $age = "",$height = "")
  8. {
  9. $this->name = $name;
  10. $this->age = $age;
  11. $this->height = $height;
  12. }
  13. public function program()
  14. {
  15. return $this->name . ', 年龄: ' . $this->age. '身高:' . $this->height.'<br>';
  16. }
  17. }
  18. $fugen = new people("张福根","18岁","188CM");
  19. echo $fugen->name,'<br>';
  20. echo $fugen->program();

二、self关键字:

  1. <?php
  2. // self是类内部代替类名的关键字,
  3. // self::静态成员 完成本类中静态成员的访问,
  4. // * 类名::静态成员 完成类外部和成员方法中静态成员的访问
  5. class User{
  6. public $name = "张福根";
  7. public static $age = 21;
  8. static function getAge()
  9. {
  10. echo '年龄:'.User::$age.'<br>';
  11. echo '年龄:'.self::$age.'<br>';
  12. }
  13. }
  14. User::getAge();
  15. `

三、final关键字:

  1. <?php
  2. // final:加在类前,表示该类不能被继承,加在方法前,表示该方法不能被重写
  3. final class BaseClass {
  4. public function test() {
  5. echo " my name is fugen<br>";
  6. }
  7. // 这里无论是否将方法声明为final,都没有关系
  8. final public function moreTesting() {
  9. echo "我 is 福根<br>";
  10. }
  11. }
  12. class ChildClass extends BaseClass {
  13. }
  14. $fugen =new BaseClass();
  15. $fugen->test();
  16. // Fatal error: Class ChildClass may not inherit from final class (BaseClass)

案例总结:

  • 对象引用$this,代表本对象,专门完成对象内部成员的访问
  • self可以用来在类内部完成静态成员的访问(类常量),self可以在类内部来实例化对象
  • final加在类前,表示该类不能被继承,加在方法前,表示该方法不能被重写
Correcting teacher:灭绝师太灭绝师太

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
1 comments
灭绝师太 2020-12-04 13:55:17
福~你作业一直坚持,理论部分掌握了,后面实战也要加把劲~代码多敲就有感觉了~
1 floor
Author's latest blog post