I'm trying to put all my PHP functions in a separate file. I'm using require to include them in the controller file but I get errors with undefined variables in the view file.
For example:
A function stored in a file 'functions.php' validating my contact form (for the sake of clarity reduced here to validating only one field):
function validateContactForm()
{
if (empty($_POST['name'])) {
$name_error = 'Name is required.';
} else {
$name = ($_POST['name'];
if (!preg_match("/^[A-Za-z .'-]+$/", $name)) {
$name_error = 'Enter a valid name.';
}
}
}
In my controller I put this require 'functions.php';.
My view file which gives undefined variable errors. It's just an HTML file with PHP code echoing validation messages.
<form
name="contact"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
method="post">
<label
for="name"
id="name-form">
Name:
</label>
<span id="name-error">
<?php echo $name_error; ?></span>
</form>
It all works great when I put the PHP code without enclosing it in a function on top of the view file. I've tried to return $name in the function, I've tried require_once and also I used $name as an argument in the function: validateContactForm($name) .
I have followed some simple tutorials where return statement is supposed to be enough but obviously I'm missing something.
Looks like my view file can't access the variables in the function validateContactForm().
return? It's not enough to make the function return a value - you need to store that value in a variable in order to use it, e.g.$var = functionThatReturnsSomething();or perhaps directly output it likeecho functionThatReturnsSomething();. Depends on whether you're going to use it in multiple places or in a single place.