Before doing something with $error:
$error = NULL;
In some script’s saw:
$error = '';
$error = false;
$error = 0;
- Which method is ‘better’ or maybe it depends in which situation i use
it ? - What’s your suggestion ?
Depends on your design:
- Are you setting it as an Object in case of error? Use
NULL
. - Are you setting it to
true
in case of error? Usefalse
. - Are you setting it as a number of some sort in case of error? Use
0
. - Are you setting it to a string to describe the error? Use
''
.
A better way to indicate errors would be throwing Exceptions though, rather than setting a variable and determine the error according to it.
Answer:
There is no canonical answer to this question. As long as you use one of these semaphores consistently, you can use anything you want. Because PHP is loosely-typed, all of these values are “falsy” and can be evaluated in a boolean comparison as FALSE
.
That said, there is more of a difference between the empty string and the others, so I’d stick with NULL
s and FALSE
s in this sort of scenario.
Answer:
1.
$v = NULL;
settype($v, 'string');
settype($v, 'int');
settype($v, 'float');
settype($v, 'bool');
settype($v, 'array');
var_dump($v);
2.
$v = NULL;
var_dump( (string) $v);
var_dump( (int) $v);
var_dump( (float) $v);
var_dump( (bool) $v);
var_dump( (array) $v);
Answer:
It depends upon the conditions where you need to use the $error
. Using a NULL
is what I chose mostly as I deal more with MySQL clauses and all!
Tags: phpphp