首页 > 代码库 > PHP类与对象

PHP类与对象

//创建一个类
class Student
{
//定义成员属性用public声明,public指的是共用的,任何地方都能访问
//姓名
public $name = ‘lemon‘;//设置初始值
//学号
public $no;
//成绩
public $score;

//成员方法
public function sing($songName){
echo "学生会唱{$songName}歌";
}

public function run(){
echo "学生去跑步了";
}

public function showSelf(){
echo "我叫".$this->name.",我的学号是{$this->no},我的成绩是{$this->score}";
$this->sing("成都");
}
}

class Teacher{
public $name;
public $no;
public $course;

public function teachBook(){
echo "老师会教书";
}

public function dance(){
echo "老师会跳舞";
}
}

//实例化对象
$student1 = new Student();
echo $student1->name;
$student1->name = ‘柠檬‘;
echo $student1->name;
$student1->sing("国");
echo"<hr>";
$student2 = new Student();
$student2->name = "张三";
$student2->no = "1001";
$student2->score = "100";
$student2->showSelf();

include "";//用来引用class类,出现错误会警告
require "";//用来引用class类,出现错误会崩溃
include_once "";//只引用一次,多次引用不会报错
require_once "";//只引用一次,多次引用不会报错

PHP类与对象