Answer the question
In order to leave comments, you need to log in
PHP assertions?
All with the coming! In Perfect Code, Steve McConnell recommends using assertions when writing code in order to make certain assumptions at any particular place in the program obvious to other programmers and to be able to catch abnormal situations when these assumptions turn out to be wrong. PHP has 2 built-in functions for working with assertions:
function doIt(){
$a = 1;
$b = 0;
//...
$b = $c[2];
assert('$a == $b'); //Для дальнейшего выполнения программы это явно предполагается. До присвоения значения $b, утверждение может быть неверно.
//...
}
Answer the question
In order to leave comments, you need to log in
In general, assertions are not for testing or checking variables, they are more for getting rid of checks. Put an assertion where you "don't want to check" the code and forget about it until you see an error message. And they are placed not where you know that there will be an error, but where _possibly_ an error may occur, but not the fact that it will happen at all. Asserts can be scattered in such places and simply forgotten about them until the error message. They are also turned off globally, so you can not remove them even after the release of the project, but only turn it off on the live.
I haven't seen many exceptions. and you are talking about assertions.
I used to use assert('is_*($param)') to control the type of function parameters, but somehow I abandoned this practice, because it never worked.
We use the onPHP framework, which has the Assert class. We use not that actively, but still.
The most typical case: you need to check that the config is filled with the necessary parameters. It's much more compact to use an assert instead of a bunch of ifs.
In which case, an exception is thrown by WrongStateException, but this is handled differently. In extreme cases, stop the application and write to the log.
We use a construct like if($unforseenCondition) trigger_error ('Unforseen happened') as assertions. Depending on the unforeseen or abnormal situation, these may be different levels of alerts .
Errors in test environments are turned into exceptions using set_error_handler (), and in production they are collected using NewRelic (read more here ).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question