PHP 面向对象编程

时间:2022-05-10 16:45:23

面向对象——类:

  创建一个类:

    

 //创建了一个没有内容的Person(人)类
class Person{ }
//通过new关键字来 实例化一个类
$teacher = new Person; //teacher属于Person类
$student = new Person; //学生也是人的种类

  类的属性:

 //类的属性相当于我们平常在PHP中说的变量
class Person{
public $isAlive = true;
public $firstName;
public $lastName;
public $age; } $teacher = new Person;
//访问类的isAlive属性 将会输出1(代表true 0代表false)
echo $teacher->isAlive;

  类的属性(2):

 class Person{
punlic $isAlive = true;
public $firstname;
public $lastname;
public $age; //构造器函数(方法) 实例化时会自动执行这个方法
public function __construct($firstname,$lastname,$age){
//$this关键字来指定这个类 把得到的值赋值给属性$firstname
$this->$firstname = $firstname;
$this->$lastname = $lastname;
$this->$age = $age; } } $person1 = new Person("Fake","Face",20);
echo $person1->age;//输出20

  类的方法:

  class Person{
public $isAlive = true;
public $firstname;
public $lastname;
public $age; public function __construct($firstname,$lastname,$age){
$this->firstnmae = $firstname;
$this->lasename = $lastname;
$this->age = $age; }
//这是一个方法
public function greet(){
return "Hello, my name is".$this->firstname." ".$this->lastname.". Nice to meet you!:-)";
}
} $student = new Person("Fake","Face",20);
echo $student->age;//输出20
echo $student->greet();//类的greet方法(相当于函数)