💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 一、概述 php通过class关键字声明类,其中一个类包含属性和方法两部分;某类事物的实例,比如人类指类,那单个人就是对象。 ``` class Person { # 属性 private $name = "cercy"; public $sex = "girl"; protected $height = 1.88; # 方法 public function setName($name){ $this->name = $name; } public function getName(){ return $this->name; } } # 实例化一个对象 $myObject = new Person(); echo $myObject->name; echo $myObject->getName(); ``` ## 二、构造函数 类中存在默认的构造函数,也可以指定构造函数,用于在实例化对象时指定属性而不是使用默认的属性,构造函数自动执行,无需手动调用。 ``` class Person { private $name = "jimson"; public $sex = "boy"; public function getName(){ return $this->$name; } public function __construct($name,$sex){ $this->$name = $name; $this->$sex = $sex; } } $newObj = new Person("Tim","girl"); ``` ## 三、析构函数 也是自动执行的函数,用于实例化对象之后将类销毁。 ``` class Person { # …… public function __destruct(){ echo __CLASS__."被销毁了"; } } $newObj = new Person("Tim","girl"); ``` ## 四、继承 可以通过关键字extends来定义类,被继承的类叫父类,以此继承父类的非private属性和方法。 ``` class Person { private $name = "jimson"; public $sex = "boy"; public function getName(){ return $this->$name; } public function __construct($name,$sex){ $this->$name = $name; $this->$sex = $sex; } } class Teacher extends Person{ public $salary = "3000"; public function teachStudent(){ echo "传授学生知识"; } } $teacher = new Teacher("james","boy"); # 调用父类的方法 $teacher->getName(); # 调用自己的方法 $teacher->teachStudent(); ``` 子类也可以用自己的构造函数,同时调用父类的构造函数。 ``` class Person { private $name = "jimson"; public $sex = "boy"; public function getName(){ return $name; } public function __construct($name,$sex){ $this->$name = $name; $this->$sex = $sex; } } class Teacher extends Person{ public $salary = "3000"; public function getSalary(){ return $this->$salary; } public function __construct($name,$sex,$salary){ # 调用父类的构造函数 parent::__construct($name,$sex); $this->$salary = $salary; } } $teacher = new Teacher("james","boy","10000"); echo $teacher->getName(); //james echo $teacher->getSalary(); //10000 ```