I need help with php:
I am developing a certain web application with which I need a certain condition to be met for the rest of the code to be executed. For now I have developed the following, although I find it very cumbersome to see:
if ($message != 'Mensaje') {
echo '¡El mensaje está mal escrito!';
} else {
echo '¡El texto del mensaje es correcto!';
// Aquí hay otras 800 líneas de código.
}
As you can see from the annotation, there is a lot of code in the else
. When these types of statements accumulate, the code becomes more and more "dirty", which does not interest me.
Is there a way to not have to use else
? Namely:
if ($message != 'Mensaje') {
echo '¡El mensaje está mal escrito!';
// Sentencia que pone fin al código, tal y como lo hace un require; cuando suelta un error.
}
echo '¡El texto del mensaje es correcto!';
// Aquí hay otras 800 líneas de código.
In this way, the first code and the second would give the same results with the exception that the second is much cleaner than the first. Until now I had searched for information about require
, but apparently it only works if it is about checking the existence of certain files. Is there a way to get the same results as with require
using variables?
A greeting and good programming.
You can do it perfectly but instead of using a
echo
use areturn
, but you must have the validation inside a function.return returns control of the program to the calling module. Execution returns to the next expression after the calling module.
If called from a function, the return statement immediately terminates execution of the current function, and returns its argument as the value of the function call. return also terminates the execution of an eval() statement or script file.
That is, you must do it this way:
Now, if you want to do it with an echo, which I don't recommend, then you can place an
exit()
where you want the script execution to stop.exit — Prints a message and ends the current script
Ends the execution of the script. shutdown functions and destructor objects will always be executed even if the exit function is called.
Exit is a language construct and can be called without parentheses if no status is passed to it.
Now, if what you want is to reuse code, I recommend working with classes and objects, or at least with a function that returns you
true
orfalse
depending on what is fulfilled.Source: https://www.php.net/manual/es/function.exit.php
Source: https://www.php.net/manual/es/function.return.php