大网数据广告活动
PHP 语言与运行手册

Pdo\Sqlite::createFunction · Registers a user-defined function for use in SQL statements

· 52CE 我爱测

Pdo\Sqlite::createFunction — Registers a user-defined function for use in SQL statements

Pdo\Sqlite::createFunction

(PHP 8 >= 8.4.0)

Pdo\Sqlite::createFunction — Registers a user-defined function for use in SQL statements

说明

public function Pdo\Sqlite::createFunction(
    string $function_name,
    callable $callback,
    int $num_args = -1,
    int $flags = 0
): bool

This method allows PHP function to be registered with SQLite as a user-defined function, so that it can be called within SQL queries. The defined function can be used in any SQL query that allows function calls, for example SELECT, UPDATE, or triggers.

小技巧

By using this method it is possible to override native SQL functions.

参数

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

注意:

Callback functions should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as:

function callback(mixed $value, mixed ...$values): mixed
value

The first argument passed to the SQL function.

values

Further arguments passed to the SQL function.

num_args

The number of arguments that the SQL function takes. If this parameter is -1, then the SQL function may take any number of arguments.

flags

A bitmask of flags. Currently, only Pdo\Sqlite::DETERMINISTIC is supported, which specifies that the function always returns the same result given the same inputs within a single SQL statement.

返回值

成功时返回 true, 或者在失败时返回 false。

示例

示例 #1 Pdo\Sqlite::createFunction() example

In this example, we have a function that calculates the SHA256 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that there is no need to process the result using a foreach loop after the query.

<?php
function sha256_and_reverse($string)
{
    return strrev(hash('sha256', $string));
}

$db = new Pdo\Sqlite('sqlite::sqlitedb');
$db->createFunction('sha256rev', 'sha256_and_reverse', 1);
$rows = $db->query('SELECT sha256rev(filename) FROM files')->fetchAll();
?>

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。