PHP 面向对象编程

面向对象——类:

  创建一个类:

    

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

  类的属性:

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

  类的属性(2):

 1 class Person{
 2     punlic $isAlive = true;
 3     public $firstname;
 4     public $lastname;
 5     public $age;
 6 
 7     //构造器函数(方法) 实例化时会自动执行这个方法
 8     public function __construct($firstname,$lastname,$age){
 9         //$this关键字来指定这个类 把得到的值赋值给属性$firstname
10         $this->$firstname = $firstname;
11         $this->$lastname = $lastname;
12         $this->$age = $age;
13       
14     }
15 
16 
17 }
18 
19 $person1 = new Person("Fake","Face",20);
20 echo $person1->age;//输出20

  类的方法:

 1  class Person{
 2                 public $isAlive = true;
 3                 public $firstname;
 4                 public $lastname;
 5                 public $age;
 6                 
 7                 public function __construct($firstname,$lastname,$age){
 8                     $this->firstnmae = $firstname;
 9                     $this->lasename = $lastname;
10                     $this->age = $age;
11                     
12                 }
13                 //这是一个方法
14                 public function greet(){
15                     return "Hello, my name is".$this->firstname." ".$this->lastname.". Nice to meet you!:-)";
16                 }
17             }
18             
19             $student = new Person("Fake","Face",20);
20             echo $student->age;//输出20
21             echo $student->greet();//类的greet方法(相当于函数)
22           
原文地址:https://www.cnblogs.com/linuxroot/p/3165679.html