2.13.PHP7.1 教程- -【PHP 类】

#目录
博客目录

http://www.foxwho.com/article/24

CSDN目录

http://blog.csdn.net/fenglailea/article/details/60330101

风.fox
#PHP 类
class 开头, 类名 及一对花括号

类名由字母或下划线开头,后面由字母,数字或下划线组成。

一个类可以包含有属于自己的常量,变量(称为“属性”)以及函数(称为“方法”)。

类内部的属性(变量)或者方法,可以用变量 $this内部调用

$this 是一个到主叫对象的引用(通常是该方法所从属的对象,但如果是从第二个对象静态调用时也可能是另一个对象)。

class Test{
	const LEV=1;
	private $name="测试名称";
	public function check(){
		echo $this->name;
		...
	}
	public function show(){
		$this->check();
	}
	//.......
}

#类中 静态成员,类常量 访问用范围解析操作符 ::
在类中 访问 静态成员,类常量,用::号访问(2个冒号)

#类中访问控制
public 公有,公共的,外部可以访问

protected 受保护(当前类及其子类都可以使用),只有内部使用

private 私有的,只有内部使用

class Test{
	public const LEV=1;//公共常量
	private $name="测试名称";//私有属性
	public $name="测试名称";//公共属性
	protected $level="22";//受保护的属性
	//公共方法
	public function check(){
		echo $this->name;
		echo $this->name;
		echo $this->level;
		...
	}
	//公共方法
	public function show(){
		$this->check();
		echo $this->name;
		echo $this->level;
	}
	//受保护的方法
	protected function format(){
		$this->check();
		$this->total();
		echo $this->name;
		echo $this->level;
	}
	//私有方法
	private function total(){
		$this->check();
		echo $this->name;
		echo $this->level;
	}
	//.......
}
//
$t=new Test();
echo $t->name;//公共属性
$t->show();//公共方法

#类的继承
一个类继承另一个类用 extends 关键字

一个类继承只能继承一个类,不能同时继承多个类
继承将会影响到类与类,对象与对象之间的关系
子类就会继承父类所有公有的和受保护的方法,除非子类覆盖了父类的方法,被继承的方法都会保留其原有功能。

class Test{
	public const LEV=1;//公共常量
	private $name="测试名称";//私有属性
	public $name="测试名称";//公共属性
	protected $level="22";//受保护的属性
	//公共方法
	public function check(){
		echo $this->name;
		echo $this->name;
		echo $this->level;
		...
	}
	//公共方法
	public function show(){
		$this->check();
		echo $this->name;
		echo $this->level;
	}
	//受保护的方法
	protected function format(){
		$this->check();
		$this->total();
		echo $this->name;
		echo $this->level;
	}
	//私有方法
	private function total(){
		$this->check();
		echo $this->name;
		echo $this->level;
	}
	//.......
}

class TestChild extends Test{
	public function all(){
		echo $this->check();
		echo $this->format();
		echo self::LEV;
		echo $this->level;
	}
}

$t=new TestChild();
echo $t->name;//公共属性 父类的属性
$t->show();//公共方法   父类的方法
$t->all();//公共方法