Blogger Information
Blog 23
fans 0
comment 3
visits 15236
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP类和对象的基础学习——php线上第九期
木易
Original
718 people have browsed it

1. 创建类、实例化、命名空间、类成员、类方法(手写)



  1. <?php
  2. //定义类
  3. class people{
  4. }
  5. //实例化类
  6. $o1 =new people();
  7. //数据类型object
  8. var_dump($o1);
  9. echo'<hr>';
  10. //判断是否属于同个类的实例
  11. var_dump($o1 instanceof people);
  12. $o2 =new people();
  13. echo '<hr>';
  14. //两个对象虽然同属于一个类的实例,但是彼此不全相等
  15. var_dump($o1==$o2);
  16. echo '<hr>';
  17. var_dump($o1 === $o2);
  18. echo '<hr>';
  1. <?php
  2. //命名空间:解决全局成员的命名冲突问题
  3. //namespace red;
  4. //class Test{
  5. //
  6. //}
  7. //namespace blue;
  8. //class Test{
  9. //
  10. //}
  11. //也可以使用大括号来声明
  12. // namespace one{
  13. // class Test{}
  14. // }
  15. $name ='网络摄像机';
  16. class A{
  17. public $name='网络摄像机';
  18. public $price ='700';
  19. }
  20. $a =new A();
  21. // 访问类的成员:->,访问成员和方法
  22. echo $a -> price;
  23. //动态对象属性
  24. $a -> brand = '华为';
  25. echo $a -> brand;
  26. //对象方法
  27. class B{
  28. public $name ='人类';
  29. public $color = '黄色';
  30. public function chifan(){
  31. echo $this ->name.'去吃饭';
  32. }
  33. public function heshui(){
  34. echo '欧文要喝水';
  35. }
  36. public function newlei(){
  37. $b =new self();
  38. echo $b -> chifan();
  39. }
  40. }
  41. //类外实例化
  42. $ren = new B();
  43. print_r(get_class_methods(B::class));
  44. $ren -> chifan();
  45. echo '<hr>';

2. 构造方法

  1. //构造方法:初始化对象成员,_construct()
  2. class C{
  3. public $name;
  4. public $age;
  5. public function __construct($name,$age){
  6. $this ->name = $name;
  7. $this -> age = $age;
  8. echo $this -> name .$this ->age;
  9. }
  10. // 析构方法:在对象被删除时清理时自动调用
  11. public function __destruct(){
  12. echo '对象删除';
  13. }
  14. }
  15. //当类实例化就会立即执行构造方法
  16. $a = new C('木易','21');
  17. echo '<hr>';
  18. $a = new C('欧阳','18');
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