如何将全局脚本转换为函数?

How to convert a global script into a function?

大家好,我在尝试将现有脚本转换为简单函数时遇到了一个小问题。我会在下面留下我的代码。

PHP:

function service_check($postcode) {
    $op_postcodes = array(... "DG10","DG3","DG4" ...);

    if(isset(htmlentities($postcode))) {
        $postcode_checker = trim(strtoupper(htmlentities($postcode)));
        $trim_postcode = trim(substr(htmlentities($postcode_checker, 0, -3)));

        if(empty($postcode_checker)) {
            $error = "We require your postcode to check our service in your area.";
        } else if(!valid_postcode($postcode_checker)) {
            $otp = "The postcode you entered is invalid.";
        } else if(!in_array($trim_postcode, $op_postcodes)) {
            $otp = "Sorry, but we don't provide our service's in your area, just yet.";
        } else {
            $otp = "Great news! We're in your area and you are eligible to order our services!";
            $_SESSION['customer_postcode'] = $postcode_checker;
        }
    } else {
        $otp = "To get started please enter your postcode.";
    }
}

我目前使用的函数是<?php service_check($_POST['service_check']); ?>

我的错误是:

Fatal error: Cannot use isset() on the result of a function call (you can use "null !== func()" instead) in /home/domain.com/public_html/controller/application/functions/locale.SM.php on line 27

改变这个

 if(isset(htmlentities($postcode))) {

到这个

$pc = htmlentities($postcode);
if(isset($pc)) {

如果有时间,请阅读此内容 - http://php.net/manual/en/function.isset.php http://php.net/manual/en/function.htmlentities.php

由于您的问题不完整,我假设现在进行编辑。更好的方法是在我们的 if 条件下使用 !empty() 而不是 isset() 。

更好的是,从您的 if 块中删除 htmlentities 方法调用,然后在您实际需要时使用 html 实体。