# 类声明,类的实例化
<?php
// class 声明一个类
class student{
//类属性
public $name = ‘张三’;
public $age = 20;
//构造方法初始化 $name和$age变量
function __construct($name,$age){
$this -> name = $name;
$this -> age = $age;
}
public function mingzi()
{
return $this->name;
}
}
// new:类实例化
$obj = new student(‘李四’,28);
var_dump($obj);
类的静态成员
<?php
//静态成员
//static 声明静态成员
class user{
public static $name="小花";
public static $sex="女";
// public function __construct($name="张三",$sex="男"){
// self::$name = $name;
// self::$sex = $sex;
// }
public static function mingzi(){
//调用静态成员用类名::静态成员
return '我叫'.self::$name.'我是'.self::$sex;
}
}
// $yuangong=new user();
// var_dump(user::$name);
echo user::mingzi();
类的扩展
<?php
//类的扩展
class phone{
protected $name = ‘座机’;
protected $gn= ‘打电话’;
public function chi()
{
return "$this->name , $this->gn";
}
}
$elephant = new phone();
echo $elephant->chi();
class mobile extends phone {
private $yinyue = '音乐';
private $shipin = '视频';
public function zhineng(){
return "我不仅会 $this->gn ,我还会 $this->yinyue , $this->shipin";
}
}
$gongju = new mobile();
echo $gongju->zhineng();
trait功能
<?php
//通过在类中使用use 关键字,声明要组合的Trait名称,具体的Trait的声明使用Trait关键词,Trait不能实例化
trait dome1{
public $name = ‘老王’;
public function text(){
return $this->name;
}
}
class dome2{
use dome1;
}
$dome2 = new dome2();
echo $dome2->text();
trait 的冲突与优先级的解决方案
1.优先级解决
2.别名
<?php
trait student{
public function zhangsan(){
return ‘我是张三’;
}
}
trait student2{
public function zhangsan(){
return ‘我也是张三’;
}
}
class student3{
use student,student2{
//优先级
student::zhangsan insteadOf student2;
//别名
student2::zhangsan as T2zhangsan;
}
}
$student3 = new student3();
echo $student3->zhangsan().’<br>‘;
echo $student3->T2zhangsan();
trait与父类的区别与联系
子类>trait>父类
输出子类chi()
没有子类输出trait的chi()
都没有则输出父类的chi();