判断长度是否符合要求类(Length_class.php):
<?php
class Length{
protected $min;
protected $max;
//$arr的输入格式为一个数组,如['min'=>19,'max'=>29]
function __construct($arr){
$this->min = $arr["min"];
$this->max = $arr["max"];
}
//如果$value字符串长度在min和max范围内,返回true
function validate($value){
if(strlen($value)>=$this->min && strlen($value)<=$this->max){
return true;
}else{
return false;
}
}
}
?>
判断数字是否在范围内类(Age_class.php):
<?php
class Age{
protected $min;
protected $max;
//$arr的输入格式为一个数组,如['min'=>19,'max'=>29]
function __construct($arr){
$this->min = $arr["min"];
$this->max = $arr["max"];
}
//如果$value在min和max的范围中,返回true
function validate($value){
if($value>=$this->min && $value<=$this->max){
return true;
}else{
return false;
}
}
}
?>
工厂模式类(validtion_class.php):
<?php
//工厂模式,封装一个类
class Validation{
//静态属性
static $error="";
//静态方法,4个参数,分别是 调用的类名,输入的值,min和max的范围数组,错误时输出的信息
static function validate($className,$value,$params=[],$message=""){
//加载调用的类的文件,ucfirst($className)让$className变量的开头字母为大写
require(ucfirst($className)."_class.php");
//实例化类和调用validate方法
$ob = new $className($params);
$re = $ob->validate($value);
if($re){
return true;
}else{
self::$error = $message;//错误时静态属性值
为message变量的值
return false;
}
}
}
?>
调用类(validation.php):
<?php
require_once("validtion_class.php");
//调用Validation的类的validate方法,再调用Length这个类
$re = Validation::validate("length",'jjjjjjk',["min"=>10,"max"=>20],"长度不符合要求");
if(!$re){
//调用Validationd的静态的属性error
echo Validation::$error;
}
//调用Validation的类的validate方法,再调用Age这个类
$re = Validation::validate("age",23,["min"=>10,"max"=>20],"数字不>在范围内");
if(!$re){
//调用Validationd的静态的属性error
echo Validation::$error;
exit;
}
?>
图: