Answer the question
In order to leave comments, you need to log in
What should the method return?
Hello! help resolve the issue.
I'm trying to write a class to clean up data. It is assumed that all data of any form will pass through the corresponding static methods of this class.
However, the IDE swears at me how much in vain and PHP itself is also dissatisfied with my crooked hands and not very smart brains.
While trying to write a method to clear an int, I ended up with the following:
public static function cleanInt($int)
{
$int = trim($int);
try {
if ($int = (int) $int) {
return $int;
}
throw new Exception('Not int ');
} catch (Exception $e) {
echo $e->getMessage();
}
return false;
}
Answer the question
In order to leave comments, you need to log in
You cannot mix int and boolean.
There are several options here.
The simplest is to use exceptions, but it's expensive.
If the function returns 0, then in most cases it means ok. You can return -1 as an error.
Another option is to return a class like ErrorType { errorCode, errDescription }.
The variant is more difficult - to write a class, inside of which this method, but not static. And write the execution results in the fields of this class - errCode, errDescription
...
There are a lot of options, but not the same as yours
Alternatively, you can look in C#. There are implemented a couple of methods for the classes Int, Float (and others): Int.Parse(string)
and Int.TryParse(string)
. The first throws an exception in case of an error, the second silently returns 0. Depending on the logic, either one or the other is used.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question