You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复PHP Deprecated错误:必填参数位于可选参数之后的问题

PHP函数Deprecated警告修复方案

报错原因

你遇到的警告是PHP 8.0及以上版本的语法校验规则触发的:

Deprecated: Required parameter $orderfield follows optional parameter $where

规则要求:函数声明中所有带默认值的可选参数,必须放在无默认值的必选参数之后。你当前的函数里$where = NULL、$and = NULL属于可选参数,后面跟随的$orderfield没有默认值属于必选参数,不符合规则因此抛出警告。

修复方案

方案1:无需修改现有调用代码(兼容性优先)

给位于可选参数后的必选参数增加默认值,同时补充参数合法性校验,避免SQL错误,修改后的函数代码如下:

function getAllFrom($field, $table, $where = NULL, $and = NULL, $orderfield = '', $ordering = "DESC") {
    global $con;
    // 排序字段为必传,为空时主动抛出错误避免SQL语法异常
    if (empty($orderfield)) {
        throw new \InvalidArgumentException('排序字段$orderfield不能为空');
    }
    $getAll = $con->prepare("SELECT $field FROM $table $where $and ORDER BY $orderfield $ordering");
    $getAll->execute();
    $all = $getAll->fetchAll();
    return $all;
}

该方案不需要修改你已有的函数调用代码,警告即可消除。

方案2:调整参数顺序(规范编码优先)

按照PHP语法规范调整参数顺序,将所有必选参数放在最前面,可选参数统一放在末尾,修改后的函数代码如下:

function getAllFrom($field, $table, $orderfield, $where = NULL, $and = NULL, $ordering = "DESC") {
    global $con;
    $getAll = $con->prepare("SELECT $field FROM $table $where $and ORDER BY $orderfield $ordering");
    $getAll->execute();
    $all = $getAll->fetchAll();
    return $all;
}

⚠️ 采用该方案需要同步修改所有调用该函数的传参顺序,你给出的调用代码需要调整为:

<?php
// 排序字段Item_ID调整到第三个参数位
$allItems = getAllFrom('*', 'items', 'Item_ID', 'where Approve = 1', '');
foreach ($allItems as $item) {
    echo '<div class="col-sm-6 col-md-3">';
    echo '<div class="thumbnail item-box">';
    echo '<span class="price-tag">$' . $item['Price'] . '</span>';
    echo '<img class="img-responsive" src="img.png" alt="" />';
    echo '<div class="caption">';
    echo '<h3><a href="items.php?itemid='. $item['Item_ID'] .'">' . $item['Name'] .'</a></h3>';
    echo '<p>' . $item['Description'] . '</p>';
    echo '<div class="date">' . $item['Add_Date'] . '</div>';
    echo '</div>';
    echo '</div>';
    echo '</div>';
}
?>

内容的提问来源于stack exchange,提问作者Yasir ayad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:54:01