PHP面向对象编程

面向对象编程的特性

封装,继承,多态

类和对象的概述

构造函数

当创建一个新的类的调用即声明新对象的时候,php会根据请求在内存区域创建和分配该类和属性的副本,开发者在php脚本中进行调用
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<?php
	class student{
		public $name;
		public $age;
		function sayHello(){
			echo $this->name." with the age of ".$this->age." say hello to you!";
		}
		function student($name,$age){
			$this->name=$name;
			$this->age=$age;
		}
	}

	$stu = new student('cyt',19);
	$stu->sayHello();
?>
</body>
</html>


析构函数

当一个对象即将被销毁调用的方法。
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<?php
	class student{
		public $name;
		public $age;
		function sayHello(){
			echo $this->name." with the age of ".$this->age." say hello to you!";
		}
		function __construct($name,$age){
			$this->name=$name;
			$this->age=$age;
		}
		function __destruct(){
			echo "析构函数被执行!";
		}
	}

	$stu = new student('cyt',19);
	$stu->sayHello();
	echo "</br>";
	unset($stu);
?>
</body>
</html>
PHP面向对象编程_第1张图片

静态成员

不需要将类进行实例化就可以直接访问类的内容
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<?php
	class goods{
		private static $goodno=1000;
		public static $goondname="huawei";
		public static function increno(){
			return self::$goodno++."</br>";
		}
		public function outputname(){
			echo self::$goondname."</br>";
		}
	}
	echo goods::increno();
	echo goods::increno();
	echo goods::increno();
	echo goods::increno();

?>
</body>
</html>



抽象类的使用

抽象类是一种不能被实例化的类,用于为继承的子类定义界面,在抽象类中的成员方法都是没有具体实现的方法。因此,抽象类强制开发者这能从特定的父类来继承,然后在继承的子类中完成所需的具体成员方法。
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<?php
	abstract class A{
		abstract protected function mess($name);
	}
	class B extends A{
		public function mess($name,$age=19){
			echo $name." with age of ".$age;
		}
	}
	$C = new B();
	$C->mess("cyt");

?>
</body>
</html>

final的使用

final用来声明一个方法是最终的版本,不能再重新申明,也不能被覆盖。


你可能感兴趣的:(PHP面向对象编程)