The problem is that the code ignores scope, a fundamental programming concept.
This scope:
function form_validation() {
...
$error_message="Too short!";
...
}
and this scope:
function save_to_db() {
...
... echo $error_message;...
}
Are not the same. It would be unreasonable and illogical to expect it to transfer over. When you assign $error_message
a value int he form_validation
function that variable only exists inside form_validation()
. Once that function finishes executing there are no longer references to the variable and it can be garbage collected.
When save_to_db
happens it is in a different scope, so even if the error_message
from form_validation
still existed, it would not be the same $error_message
variable.
This is why we have the global
keyword, but importantly, objects can hold state, aka class member variables. It’s one of the main reasons classes exist in the first place, and for some reason it was not used. Classes are not inherently “better”, they’re a tool, and if all you wanted was a global variable you could access anywhere, then you should have used functions instead, or return values.
The irony is that you’ve already used the solution, and done it in a way that would generate exactly the same warning:
if ( strlen($this->first_field) < 4 ) {
Nowhere in the code gives first_field
a value, or define it in any way. You have to declare that something exists before you use it, either by defining it or by giving it a value. You can’t pull things out of thin air.
Further reading: