类声明与类的实例化
class : 声明类
new : 类的实例化
class User
{
public $name = 'jack';
public $age = 28;
}
$user = new User ();
类的静态成员与类的扩展
static : 声明静态成员
调用静态成员用类名::静态成员
class User
{
public $name = 'jack';
public $age = 28;
public static $gender = 'male';
public static function show(){
return self::$gender;
}
}
echo User::$gender; // 输出 male
echo User::show(); // 输出 male
trait功能
trait 是类似于类的声明,用use调用,但是不能实例化
trait User
{
public $name = 'jack';
public $age = 28;
public static $gender = 'male';
public static function show(){
return self::$gender;
}
}
class People
{
use User;
}
$people = new People();
echo $people->show();//输出: male
trait与父类的区别与联系
基类>trait>父类
trait User
{
public $name = 'jack';
public $age = 28;
public $gender = 'male';
public function show(){
echo '这个是User的show';
}
}
class Person
{
public function show(){
echo '这个是Person的show';
}
}
class People extends Person
{
use User;
public function show(){
echo '这个是People的show';
}
}
$people = new People();
echo $people->show();
基类存在则输出的show();
基类不存在则输出trait的show();
都不存在则输出父类的show();