PHP 谓词
最后修改于 2025 年 3 月 12 日
在本文中,我们将探讨 PHP 中的谓词
。 谓词是一个返回布尔值的函数,通常用于测试条件或验证数据。 谓词对于过滤、验证或在代码中做出决策非常有用。
基本定义
谓词是一个接受一个或多个参数并返回true
或false
的函数。 谓词通常用于函数式编程中,以过滤数组、验证输入或做出决策。
简单谓词
以下示例演示了一个简单的谓词,用于检查一个数字是否为偶数。
main.php
<?php declare(strict_types=1); function isEven(int $number): bool { return $number % 2 === 0; } $result = isEven(4); echo $result ? 'true' : 'false';
在此程序中,isEven
函数是一个谓词,用于检查一个数字是否为偶数。 如果该数字为偶数,则返回true
,否则返回false
。
$ php main.php true
带有数组过滤的谓词
以下示例演示了如何使用谓词来过滤数组。
main.php
<?php declare(strict_types=1); function isPositive(int $number): bool { return $number > 0; } $numbers = [-1, 2, -3, 4, -5]; $positiveNumbers = array_filter($numbers, 'isPositive'); print_r($positiveNumbers);
在此程序中,isPositive
谓词从数组中过滤掉负数。 array_filter
函数将谓词应用于数组的每个元素。
$ php main.php Array ( [1] => 2 [3] => 4 )
带有匿名函数的谓词
以下示例演示了如何使用匿名函数作为谓词。
main.php
<?php declare(strict_types=1); $numbers = [1, 2, 3, 4, 5]; $evenNumbers = array_filter($numbers, function(int $number): bool { return $number % 2 === 0; }); print_r($evenNumbers);
在此程序中,匿名函数用作谓词,用于从数组中过滤偶数。 array_filter
函数将谓词应用于数组的每个元素。
$ php main.php Array ( [1] => 2 [3] => 4 )
带有多个条件的谓词
以下示例演示了一个带有多个条件的谓词。
main.php
<?php declare(strict_types=1); function isValidEmail(string $email): bool { return filter_var($email, FILTER_VALIDATE_EMAIL) !== false; } $emails = ['test@example.com', 'invalid-email', 'user@domain.com']; $validEmails = array_filter($emails, 'isValidEmail'); print_r($validEmails);
在此程序中,isValidEmail
谓词使用 PHP 的 filter_var
函数检查电子邮件是否有效。 array_filter
函数将谓词应用于数组的每个元素。
$ php main.php Array ( [0] => test@example.com [2] => user@domain.com )
带有对象验证的谓词
以下示例演示了一个验证对象的谓词。
main.php
<?php declare(strict_types=1); class User { public function __construct(public int $age) {} } function isAdult(User $user): bool { return $user->age >= 18; } $users = [new User(15), new User(20), new User(17)]; $adults = array_filter($users, 'isAdult'); print_r($adults);
在此程序中,isAdult
谓词根据用户的年龄检查其是否为成年人。 array_filter
函数将谓词应用于数组的每个元素。
$ php main.php Array ( [1] => User Object ( [age] => 20 ) )
带有严格类型声明的谓词
以下示例演示了带有严格类型声明的谓词。
main.php
<?php declare(strict_types=1); function isStringLong(string $text): bool { return strlen($text) > 10; } $texts = ['short', 'a longer text', 'another long text']; $longTexts = array_filter($texts, 'isStringLong'); print_r($longTexts);
在此程序中,isStringLong
谓词检查一个字符串是否长于 10 个字符。 array_filter
函数将谓词应用于数组的每个元素。
$ php main.php Array ( [1] => a longer text [2] => another long text )
来源
在本文中,我们展示了如何在 PHP 中使用谓词进行过滤、验证和决策。 谓词是编写简洁且可重用代码的强大工具。
作者
列出 所有 PHP 教程。