类与面向对象编程
- 创建类: 用
Class
关键字声明 - 成员属性前必须要有访问修饰符:
public, protected, private
;
<!-- 自动加载器 -->
<?php
/**
* 类的自动加载器 前提 类名称跟类文件名称保持一致 psr-4规范
*/
spl_autoload_register(function ($classname) {
$file = __dir__ . DIRECTORY_SEPARATOR . 'vender' . DIRECTORY_SEPARATOR . $classname . '.php';
if (!(is_file($file) && file_exists($file))) {
throw new \Exception('文件名不合法或者文件不存在');
}
require $file;
});
<!-- 声明类 -->
<?php
// 声明一个类
Class HumanResources
{
// 类属性
protected $name;
protected $age;
protected $entrantDate;
protected $department;
protected $position;
// 构造函数类实例化时自动调用
public function __construct($name, $age, $entrantDate, $department, $position, $jobResponsibilities)
{
// 类成员之间的互相访问 $this 本对象
// 1.初始化类成员 让类/对象的状态稳定下来
// 2.给对象的属性进行初始化赋值
// 3.给私有或者受保护的成员属性赋值
$this->name = $name;
$this->age = $age;
$this->entrantDate = $entrantDate;
$this->department = $department;
$this->position = $position;
$this->jobResponsibilities = $jobResponsibilities;
}
// 类方法
public function staffInfo() {
echo '姓名: ' .$this->name .'<br>';
echo '年龄: ' .$this->age .'<br>';
echo '入职日期: '.$this->entrantDate .'<br>';
echo '部门: ' .$this->department .'<br>';
echo '职务: ' .$this->position .'<br>';
echo '岗位职责: ' .$this->jobResponsibilities.'<br>';
}
}
<!-- 在客户端自动加载调用类 -->
<?php
require 'autoload.php';
$name = 'help';
$age = '28';
$entrantDate = '2020';
$department = 'HrDepart';
$position = 'humanSupervisor';
$jobResponsibilities = 'salaryAccounting';
$hr = new HumanResources($name, $age, $entrantDate, $department, $position, $jobResponsibilities);
$hr->staffInfo();
echo '<hr>';