PHP8.1只读属性是否与BIND_PARAM兼容?

下面是我的构造函数

public function __construct(
    private readonly ?bool $alreadyLive, //If true, the article is already live and will be updated. If false, it is a new article
    private readonly bool $pushLive, //If true, the article will be pushed live. If false, it will be saved in pending_articles
    private string $articleTitle,
    private string $articleExcerpt,
    private string $articleContent,
    private string $imageCard,
    private readonly string $articleType,
    private readonly string $articleStatus,
    private readonly ?int $articleNumber,
    private readonly int $authorID,
    private readonly int $heroPosition,
    databaseconnection $db
) {
    $this->db = $db;
}

我正在try 将一些数据插入到数据库中,如下所示:

    try {
        $sql = "INSERT INTO " . $table . " 
                    (title, author, content, excerpt, image_card, 
                    views, hero_position, type, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("sisssiiss", 
                $this->articleTitle, $this->authorID, 
                $this->articleContent, $this->articleExcerpt, 
                $this->imageCard, $views, $this->heroPosition, 
                $this->articleType, $this->articleStatus
            );
        $stmt->execute();
        $article_id = $stmt->insert_id;
        $stmt->close();
    } catch (\Exception) {
        //Rollback the transaction
        $connection->rollback();

        //Return error message
        $response['status'] = 'error';
        $response['message'] = 'There was an error submitting your article. Please try again.';
        return $response;
    }

但我一直收到这样的错误:

Cannot modify readonly property article::$authorID

根据堆栈跟踪中的行,它是由此行引起的:

$stmt->bind_param("sisssiiss", $this->articleTitle, $this->authorID, $this->articleContent, $this->articleExcerpt, $this->imageCard, $views, $this->heroPosition, $this->articleType, $this->articleStatus);

推荐答案

这个错误是绝对正确的.您不能修改readonly属性,但也不能在写上下文中使用它们.在PHP中,通过引用传递参数是considered a read-write operation.因此,不允许将只读属性传递给bind_param(),就像不允许传递常量或文字一样.

要解决此问题,请使用execute()并将值作为数组传递.

$stmt = $mysqli->prepare();
$stmt->execute([
    $this->articleTitle,
    // ...
]);

或者从PHP8.2开始,您可以使用execute_query():

$mysqli->execute_query($sqlQuery, [
    $this->articleTitle,
    // ...
]);

Php相关问答推荐

Laravel 9如何过滤$的项目与结果?

如何发送woocommerce订单跟踪码与短信

过滤WooCommerce管理员订单列表(+HPOS)中包含其作者产品的订单

从含有特殊字符的ANSI文本文件中读取数据是在移值,为什么?

根据未用于变体的产品属性隐藏WooCommerce发货方式

从订单项目中获取ACF WooCommerce产品价值

如何实现对数据库表中多列的唯一约束?

使注册字段UserMeta值对于WooCommerce中的每个用户是唯一的

Apache只允许index.php-不从根目录工作

WooCommerce 中一件免费产品的数量折扣

Woocommerce 中为空时隐藏显示变体自定义字段数据

在 groupBy laravel 5.7 中 Select 多列

Composer自动加载器重复了子类的类文件路径

如何使用 WhatsApp Cloud API 向 WhatsApp 发送消息,而无需在发送消息之前注册收件人号码?

来自 GoDaddy 的邮箱在 Gmail 中显示为via

为什么在 phpunit 的开头测试 PHP_VERSION?

Laravel Docker 几个数据库

如何在 Process facade 中转义特殊字符?

将样式文件或脚本引入WordPress模板

从 d-m-Y 日期格式 laravel 计算月份 = 01 的列的总和