- PHP function param type best practises
- // Title is expected to be string, comment_num is expected to be int
- function example1($title, $comment_num) {
- // Doesnt throw error, just converts type
- $title = (string) $title;
- $comment_num = (int) $comment_num;
- }
- // Title is expected to be string, comment_num is expected to be int
- function example2($title, $comment_num) {
- if (!is_string($title)) {
- trigger_error('String expected for first parameter', E_USER_WARNING);
- return;
- }
- if (!is_string($title)) {
- trigger_error('Int expected for second parameter', E_USER_WARNING);
- return
- }
- }
- function __type_check($params) {
- if (count($params) < 1) {
- return;
- }
- $types = func_get_args();
- array_shift($types);
- $backtrace = debug_backtrace();
- $backtrace = $backtrace[1];
- $global_types = array(
- 'bool' => 'boolean',
- 'int' => 'integer',
- 'float' => 'double'
- );
- $error = false;
- for ($i = 0, $j = count($types); $i < $j; ++$i) {
- if (strpos($types[$i], ',') === false) {
- $type = strtolower($types[$i]);
- if (isset($global_types[$type])) {
- $type = $global_types[$type];
- }
- if (gettype($params[$i]) != $type) {
- $error = true;
- break;
- }
- } else {
- $current_types = array_map('trim', explode(',', $types[$i]));
- foreach ($current_types as $type) {
- $type = strtolower($type);
- if (isset($global_types[$type])) {
- $type = $global_types[$type];
- }
- if (gettype($params[$i]) == $type) {
- continue 2;
- }
- }
- $error = true;
- break;
- }
- }
- if ($error) {
- trigger_error($backtrace['function'] . '() expects parameter ' . ($i + 1) . ' to be ' . $types[$i] . ', ' . gettype($params[$i]) . ' given', E_USER_WARNING);
- return false;
- }
- return true;
- }
- function string_manipulation($str, $str2, $offset = 1) {
- if (!__type_check(func_get_args(), 'string', 'string', 'int,float')) {
- return false;
- }
- // do manipulation here
- }
- function example1($title, $comment_num) {
- // do some operations that should work error-free regardless of type
- if ($result != 'something specific you expect here') {
- throw new Exception('Something went wrong!');
- // or
- trigger_error('Something went wrong!');
- return false;
- }
- // continue with $result
- }
- function example1(TitleObject $title) {
- // rest assured that $title is of the right type
- }