PHP - returns different types of values ​​from the same method

it would be wrong practice to return different types from the same method in php. There may be a better example for this, but essentially I want my method to do something, and if it could not return a string error message, but if it works, return true. This does not seem to me completely correct, but the only way with which this work can be done is to return a line for the error message and a line with something like "worked out" or "valid" or something else if everything goes well . Again, this means that there are more connections between methods that use this, because they cannot just check true for false, but must know a word that will represent a valid response from the method.

+3
source share
6 answers

If you are trying to control the function, you are best off using Exceptions. As with all programming languages ​​that provide them, they point to “exceptional” cases outside the expected flow of the program and do not require any return to indicate that something went wrong. See the related documentation below for PHP specifics.

PHP Exceptions

+2
source

Assuming you are referring to a method in a class, it would be better to just return TRUE or FALSE from the method, but use the $ _error property in the class, which may contain an array of error messages.

, , $_error, get_error().

+2

, , , true/false, , .

0

, , PHP, . Esp, - . , , , .

, , - , .

:

   $msg = MyFunc( $o);
    if ($msg == 'OK')   //or ($msg == 0)
    {
        //use the returned object or value
        $o->Foo();
    }
    else
    {
        //respond to error
    }
0

true - . . , . .

. , . .

, exception.

0

PHP - , PHP, .

, mysql_query() boolean false. , , mysql_error(), .

$query = mysql_query($sql);
if ($query === false) {
  die(mysql_error());
}

OO . :

$result = $search->find($keyword);

if ($result === null) {
  // no entry matches $id
} elseif ($result instanceof ResultClass) {
  // one row found; do something with the result
  print $result;
} elseif ($result instanceof ResultCollection) {
  foreach ($result as $element) {
    print $element;
  }
} else {
  // are there other types for $result?
}

, find()!

, find() ResultCollection. , . , , :

$result = $search->find($keyword);
foreach ($result as $element) {
  print $element;
}
0

Source: https://habr.com/ru/post/1754688/


All Articles