5.25 PHP

抽象类+多态

<?php
	abstract class Person{//抽象基类
		abstract public function show();//抽象方法
	}
	class Student extends Person{
		public function show(){//实现抽象方法
			echo '学生'.'<br>';
		}
	}
	class Teacher extends Person{
		public function show(){//实现抽象方法
			echo '教师'.'<br>';
		}
	}
	function show($obj){//多态
		if($obj instanceof Person){
			$obj->show();
		}
		else{
			echo '错误'.'<br>';
		}
	}
	$s1 = new Student();
	$s2 = new Teacher();
	show($s1);
	show($s2);
?>

重载 __toString()

<?php
	class Student{
		protected $name;
		protected $score;
		function __construct($name,$socre=100){
			$this->name = $name;
			$this->score = $score;
		}
		public function __toString(){
			return "{$this->name}的成绩为:{$this->score}分<br>";
		}
	}
	$s1 = new Student('LY',100);
	echo $s1;
?>

工厂模式 动态实例化有共同接口的类

<?php
	interface connect{
		public function operate();
	}
	class MySQL implements connect{
		public function operate(){
			echo 'MySQL now<br>';
		}
	}
	class SQLite implements connect{
		public function operate(){
			echo 'SQLite now<br>';
		}
	}
	class Db{
		public static function factory($type){
			if($type=='MySQL'||$type=='SQLite')
				return new $type();
			else{
				echo 'Error!<br>';
				return 'Error';
			}
		}	
	}
	$mysql = Db::factory('MySQL');
	if($mysql!='Error')$mysql->operate();
	$sqlite = Db::factory('SQLite');
	if($sqlite!='Error')$sqlite->operate();
?>

PHP的数组操作

<?php
	$arr1 = array(
		'id' => 12,
		'lover' => 13,
		'asd' => 14,
		'lover2' => 13,
	);
	var_dump($arr1);
	echo "<br>";
	unset($arr1['id']);
	var_dump($arr1);
	echo "\n";
	foreach($arr1 as $key => $value){
		echo "{$key} => {$value}"."<br>";
	}	
	echo "数组元素的个数为:".count($arr1)."<br>";
	$arr2 = array_unique($arr1);//移除重复元素
	var_dump($arr2);
	echo "去重后数组元素的个数为:".count($arr2)."<br>";
?>
posted @ 2023-05-25 16:22  N0zoM1z0  阅读(20)  评论(0编辑  收藏  举报