php笔记(8)静态属性访问

父类Person,子类student

class Person{
	//静态属性,访问方式:self/parent/static 非静态:$this->
	public static  $name='令狐冲';
	protected static  $age=200;
	private static  $sex='male';
	//静态方法
	public static function show(){
		//静态属性只允许在静态方法中访问,静态方法不允许使用伪变量$this->访问,self::表示当前类
		return '我的名字是'.self::$name.",年龄:".self::$age.'性别:'.self::$sex;
	}
}
class Student extends Person{
    public static $job='侠客';
    //静态方法
	public static function display(){
		//parent::$age引用父类中的静态成员,self::$job当前子类的属性
		return '年龄:'.parent::$age.'职业:'.self::$job;
	}
}
//外部访问静态成员/方法,使用类名::静态成员/静态属性必须加$符号
echo Person::$name;//令狐冲
echo Person::show();//我的名字是令狐冲,年龄:200性别:male

$student=new Student();
echo $student->display();//年龄:200职业:侠客,对象可以正常访问静态方法


猜你喜欢

转载自blog.csdn.net/weixin_42881256/article/details/82814333