ASCII码 ASCII码

类的自动加载

发布于:2022-02-20 11:08:34  栏目:技术文档

类与面向对象编程

  • 创建类: 用Class关键字声明
  • 成员属性前必须要有访问修饰符:public, protected, private;

<!-- 自动加载器 -->

  1. <?php
  2. /**
  3. * 类的自动加载器 前提 类名称跟类文件名称保持一致 psr-4规范
  4. */
  5. spl_autoload_register(function ($classname) {
  6. $file = __dir__ . DIRECTORY_SEPARATOR . 'vender' . DIRECTORY_SEPARATOR . $classname . '.php';
  7. if (!(is_file($file) && file_exists($file))) {
  8. throw new \Exception('文件名不合法或者文件不存在');
  9. }
  10. require $file;
  11. });

<!-- 声明类 -->

  1. <?php
  2. // 声明一个类
  3. Class HumanResources
  4. {
  5. // 类属性
  6. protected $name;
  7. protected $age;
  8. protected $entrantDate;
  9. protected $department;
  10. protected $position;
  11. // 构造函数类实例化时自动调用
  12. public function __construct($name, $age, $entrantDate, $department, $position, $jobResponsibilities)
  13. {
  14. // 类成员之间的互相访问 $this 本对象
  15. // 1.初始化类成员 让类/对象的状态稳定下来
  16. // 2.给对象的属性进行初始化赋值
  17. // 3.给私有或者受保护的成员属性赋值
  18. $this->name = $name;
  19. $this->age = $age;
  20. $this->entrantDate = $entrantDate;
  21. $this->department = $department;
  22. $this->position = $position;
  23. $this->jobResponsibilities = $jobResponsibilities;
  24. }
  25. // 类方法
  26. public function staffInfo() {
  27. echo '姓名: ' .$this->name .'<br>';
  28. echo '年龄: ' .$this->age .'<br>';
  29. echo '入职日期: '.$this->entrantDate .'<br>';
  30. echo '部门: ' .$this->department .'<br>';
  31. echo '职务: ' .$this->position .'<br>';
  32. echo '岗位职责: ' .$this->jobResponsibilities.'<br>';
  33. }
  34. }

<!-- 在客户端自动加载调用类 -->

  1. <?php
  2. require 'autoload.php';
  3. $name = 'help';
  4. $age = '28';
  5. $entrantDate = '2020';
  6. $department = 'HrDepart';
  7. $position = 'humanSupervisor';
  8. $jobResponsibilities = 'salaryAccounting';
  9. $hr = new HumanResources($name, $age, $entrantDate, $department, $position, $jobResponsibilities);
  10. $hr->staffInfo();
  11. echo '<hr>';

相关推荐
阅读 +