本文目录导读:

我来为你介绍几种创建和使用 PHP 工具函数库的方法:
简单函数库(面向过程)
创建工具文件 helpers.php
<?php
// 字符串工具函数
function str_contains_any($haystack, array $needles) {
foreach ($needles as $needle) {
if (strpos($haystack, $needle) !== false) {
return true;
}
}
return false;
}
function generate_uuid() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
// 数组工具函数
function array_flatten(array $array) {
$result = [];
array_walk_recursive($array, function($value) use (&$result) {
$result[] = $value;
});
return $result;
}
// 格式化函数
function format_bytes($bytes, $precision = 2) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
使用方式
<?php require_once 'helpers.php'; // 使用工具函数 echo generate_uuid(); echo format_bytes(1024 * 1024); // 输出: 1.00 MB
类库封装(面向对象)
创建工具类 StringHelper.php
<?php
namespace App\Helpers;
class StringHelper
{
public static function truncate($str, $length = 30, $suffix = '...')
{
return mb_strlen($str) > $length
? mb_substr($str, 0, $length) . $suffix
: $str;
}
public static function slugify($text)
{
$text = preg_replace('~[^\pL\d]+~u', '-', $text);
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
$text = preg_replace('~[^-\w]+~', '', $text);
$text = trim($text, '-');
$text = preg_replace('~-+~', '-', $text);
$text = strtolower($text);
return empty($text) ? 'n-a' : $text;
}
public static function random($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
}
数组工具类 ArrayHelper.php
<?php
namespace App\Helpers;
class ArrayHelper
{
public static function get(array $array, $key, $default = null)
{
if (is_null($key)) return $array;
if (isset($array[$key])) {
return $array[$key];
}
foreach (explode('.', $key) as $segment) {
if (!is_array($array) || !array_key_exists($segment, $array)) {
return $default;
}
$array = $array[$segment];
}
return $array;
}
public static function sortBy(array $array, $key, $order = 'asc')
{
usort($array, function($a, $b) use ($key, $order) {
$aVal = self::get($a, $key, '');
$bVal = self::get($b, $key, '');
if ($order === 'desc') {
return $bVal <=> $aVal;
}
return $aVal <=> $bVal;
});
return $array;
}
public static function removeEmpty(array $array)
{
return array_filter($array, function($value) {
return !($value === '' || $value === null || $value === []);
});
}
}
使用方式
<?php
use App\Helpers\StringHelper;
use App\Helpers\ArrayHelper;
echo StringHelper::slugify("Hello World! This is PHP");
echo StringHelper::truncate("这是一段很长的文本", 5);
$data = [
'user' => [
'name' => '张三',
'age' => 25
]
];
echo ArrayHelper::get($data, 'user.name'); // 输出: 张三
使用 Composer 管理工具库
创建 composer 包
composer.json:
{
"name": "yourname/helpers",
"description": "Collection of PHP helper functions",
"autoload": {
"files": [
"src/helpers.php"
],
"psr-4": {
"YourNamespace\\Helpers\\": "src/"
}
},
"require": {
"php": ">=7.0"
}
}
项目中使用
composer require yourname/helpers
<?php require 'vendor/autoload.php'; use YourNamespace\Helpers\StringHelper; use YourNamespace\Helpers\ArrayHelper;
常见工具函数示例
日期时间工具
<?php
function format_date($date, $format = 'Y-m-d H:i:s')
{
if (!$date) return '';
if (is_string($date)) $date = strtotime($date);
return date($format, $date);
}
function time_ago($datetime)
{
$timestamp = strtotime($datetime);
$difference = time() - $timestamp;
if ($difference < 60) return "刚刚";
if ($difference < 3600) return floor($difference / 60) . "分钟前";
if ($difference < 86400) return floor($difference / 3600) . "小时前";
if ($difference < 2592000) return floor($difference / 86400) . "天前";
return date('Y-m-d', $timestamp);
}
安全相关
<?php
function sanitize_input($input)
{
return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
function validate_email($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
function generate_token($length = 32)
{
return bin2hex(random_bytes($length));
}
最佳实践建议
- 命名规范:函数名使用动词+名词,清晰表达功能
- 单一职责:每个函数只做一件事
- 文档注释:为每个函数添加文档注释
- 参数类型检查:在函数内部进行类型检查
- 默认值:合理设置参数默认值
- 避免全局冲突:使用命名空间避免函数名冲突
<?php
/**
* 生成安全的随机密码
*
* @param int $length 密码长度
* @param bool $allowSpecialChars 是否包含特殊字符
* @return string 生成的密码
*/
function generate_password($length = 12, $allowSpecialChars = true)
{
$lowercase = 'abcdefghijklmnopqrstuvwxyz';
$uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$digits = '0123456789';
$special = '!@#$%^&*()_+-=[]{};:,.<>?';
$pool = $lowercase . $uppercase . $digits;
if ($allowSpecialChars) {
$pool .= $special;
}
$password = '';
$poolLength = strlen($pool);
// 确保至少包含每种字符类型
$password .= $lowercase[rand(0, 25)];
$password .= $uppercase[rand(0, 25)];
$password .= $digits[rand(0, 9)];
if ($allowSpecialChars) {
$password .= $special[rand(0, strlen($special) - 1)];
}
// 填充剩余长度
for ($i = strlen($password); $i < $length; $i++) {
$password .= $pool[rand(0, $poolLength - 1)];
}
return str_shuffle($password);
}
这些方法可以根据你的项目需求选择合适的方案,对于大型项目,建议使用 Composer 管理工具库,并通过命名空间组织代码。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播