Blogger Information
Blog 41
fans 0
comment 0
visits 30987
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP类与对象的基础概念
陈强
Original
695 people have browsed it

类声明与类的实例化

class : 声明类
new : 类的实例化

  1. class User
  2. {
  3. public $name = 'jack';
  4. public $age = 28;
  5. }
  6. $user = new User ();

类的静态成员与类的扩展

static : 声明静态成员
调用静态成员用类名::静态成员

  1. class User
  2. {
  3. public $name = 'jack';
  4. public $age = 28;
  5. public static $gender = 'male';
  6. public static function show(){
  7. return self::$gender;
  8. }
  9. }
  10. echo User::$gender; // 输出 male
  11. echo User::show(); // 输出 male

trait功能

trait 是类似于类的声明,用use调用,但是不能实例化

  1. trait User
  2. {
  3. public $name = 'jack';
  4. public $age = 28;
  5. public static $gender = 'male';
  6. public static function show(){
  7. return self::$gender;
  8. }
  9. }
  10. class People
  11. {
  12. use User;
  13. }
  14. $people = new People();
  15. echo $people->show();//输出: male

trait与父类的区别与联系

基类>trait>父类

  1. trait User
  2. {
  3. public $name = 'jack';
  4. public $age = 28;
  5. public $gender = 'male';
  6. public function show(){
  7. echo '这个是User的show';
  8. }
  9. }
  10. class Person
  11. {
  12. public function show(){
  13. echo '这个是Person的show';
  14. }
  15. }
  16. class People extends Person
  17. {
  18. use User;
  19. public function show(){
  20. echo '这个是People的show';
  21. }
  22. }
  23. $people = new People();
  24. echo $people->show();
  • 基类存在则输出的show();

  • 基类不存在则输出trait的show();

  • 都不存在则输出父类的show();

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
0 comments
Author's latest blog post