0

It may be obvious question, but I don't understand how does it work.

For the following code in PHP:

$connection = new mysqli("host","user","password","database");
$result = $connection->query("SELECT * FROM `table`;");
if($result)
{
// do something
}

I don't understand how it is possible to make an operation if ($result) on object since it's not a simple bool variable, but collection of variables and methods.

How is it possible?

How does this mechanism work?

Can I make my own objects that also allow to make "invisible" bool variable in it?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Maniues
  • 125
  • 1
  • 5
  • It *is* a simple bool value *in certain circumstances*: https://www.php.net/manual/en/mysqli.query.php#refsect1-mysqli.query-returnvalues – deceze May 04 '23 at 09:19
  • That value can either be the boolean value `false` or an object. The `if` statement in php can well work with such mixed values. Which is necessary, since php is a type weak language. So a language where any variable can assume values of arbitrary types. – arkascha May 04 '23 at 09:20
  • PHP is a loosely typed language. ANY variable will be implicitly cast to boolean when in appropriate context. – Your Common Sense May 04 '23 at 09:25
  • 1
    Note that you should never use if($result) with mysqli, it's useless *and* a bad practice. – Your Common Sense May 04 '23 at 09:25
  • @YourCommonSense so, what should I use instead? – Maniues May 04 '23 at 09:44
  • 1
    Nothing. It used to be the way to check for errors but now it's obsoleted. Mysqli will report errors without this code. See https://stackoverflow.com/a/74884566/285587 – Your Common Sense May 04 '23 at 09:56
  • Okay, but how to handle this error and give information to user such as "Internal error"? Use try-catch or something? – Maniues May 04 '23 at 10:56

0 Answers0