Utility Methods
Utility methods in PHP classes are static methods that provide general-purpose functionality which doesn't require instantiation of objects. These methods are often used for tasks that are not specific to individual object instances but are related to the class as a whole. Here are some common categories of utility methods:
Mathematical Operations
Utility methods for performing common mathematical calculations, such as addition, subtraction, multiplication, division, and more.
class MathUtility {
public static function add($a, $b) {
return $a + $b;
}
public static function multiply($a, $b) {
return $a * $b;
}
// Other mathematical operations...
}
String Manipulation
Static methods for string manipulation tasks, including formatting, parsing, validation, searching, replacing, and more.
class StringUtils {
public static function truncate($string, $maxLength) {
if (strlen($string) > $maxLength) {
return substr($string, 0, $maxLength) . '...';
}
return $string;
}
public static function capitalizeFirstLetter($string) {
return ucfirst($string);
}
// Other string manipulation methods...
}
Date and Time Operations
Utility methods for working with dates, times, and timestamps, including formatting, parsing, comparison, and manipulation.
class DateTimeUtils {
public static function formatTimestamp($timestamp, $format = 'Y-m-d H:i:s') {
return date($format, $timestamp);
}
public static function getCurrentTimestamp() {
return time();
}
// Other date and time operations...
}