请各位帮忙封装一段代码

请各位帮忙封装一段代码

请各位帮个忙,帮我把下面这段代码封装到一个函数里,我对封装不是很熟,所以请各位帮帮忙,谢谢。

[复制到剪切板]
CODE:
if ($_SESSION['name'] != $name) {
    echo (
"<script type='text/javascript'> alert('留言名与用户名不一致');history.go(-1);<\/script>");
    exit;
}
if(empty(
$_POST["sex"])) {
    echo (
"<script type='text/javascript'> alert('性别未选');history.go(-1);<\/script>");
    exit;
}
if(empty(
$_POST["email"])) {
    echo (
"<script type='text/javascript'> alert('邮箱不能为空');history.go(-1);<\/script>");
    exit;
}
function 
email($email){   
    if(
ereg("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+",$email)) {
        return 
true;
    } else {
        return 
false;
    }
}
if(
$_POST["email"]!=""){
    if(!
email($_POST["email"])) {
        echo (
"<script type='text/javascript'> alert('邮箱格式不对');history.go(-1);<\/script>");
        exit;
    }
}
if(empty(
$_POST["phone"])) {
    echo (
"<script type='text/javascript'> alert('电话不能为空');history.go(-1);<\/script>");
    exit;
}
if(!
is_numeric($_POST["phone"])) {
    echo (
"<script type='text/javascript'> alert('电话要是数字的');history.go(-1);<\/script>");
    exit;
}
if(empty(
$_POST["info"])) {
    echo (
"<script type='text/javascript'> alert('留言不能为空');history.go(-1);<\/script>");
    exit;
} ;


里边已经有一个函数了啊。就这样封装就行了

[复制到剪切板]
CODE:
function fun(){
    if (
$_SESSION['name'] != $name) {
        echo (
"<script type='text/javascript'> alert('留言名与用户名不一致');history.go(-1);<\/script>");
        exit;
    }
    if(empty(
$_POST["sex"])) {
        echo (
"<script type='text/javascript'> alert('性别未选');history.go(-1);<\/script>");
        exit;
    }
    if(empty(
$_POST["email"])) {
        echo (
"<script type='text/javascript'> alert('邮箱不能为空');history.go(-1);<\/script>");
        exit;
    }
    if(
$_POST["email"]!=""){
        if(!
email($_POST["email"])) {
            echo (
"<script type='text/javascript'> alert('邮箱格式不对');history.go(-1);<\/script>");
            exit;
        }
    }
    if(empty(
$_POST["phone"])) {
        echo (
"<script type='text/javascript'> alert('电话不能为空');history.go(-1);<\/script>");
        exit;
    }
    if(!
is_numeric($_POST["phone"])) {
        echo (
"<script type='text/javascript'> alert('电话要是数字的');history.go(-1);<\/script>");
        exit;
    }
    if(empty(
$_POST["info"])) {
        echo (
"<script type='text/javascript'> alert('留言不能为空');history.go(-1);<\/script>");
        exit;
    } 

} ;


$_SESSION 和 $_POST 都是全局变量

谢谢LS朋友的帮忙,再问一下,如果只调用其中的某一部分的代码要怎么用呢?能直接调用这个函数实现吗?

嗯。你自己试试咯。

汗,楼上的兄弟是搞啥滴???