我是PHP编程的新手,我需要帮助解决一个简单的问题。我正试图在我的表单页面中向一个名为errors的数组添加值,这样我以后就可以回显它进行验证,尽管我似乎无法从包含的函数文件中向数组添加任何内容。
我需要功能<?php require_once("functions.php") ?>
然后我创建阵列<?php $errors = array(); ?>
然后我调用包含<?php minLength($test, 20); ?>
的函数
此处的功能
function minLength($input, $min) {
if (strlen($input) <= $min) {
return $errors[] = "Is that your real name? No its not.";
} else {
return $errors[] = "";
}
}
然后在结束时将它们回声出来
<?php
if (isset($errors)) {
foreach($errors as $error) {
echo "<li>{$error}</li><br />";
}
} else {
echo "<p>No errors found </p>";
}
?>
但最终没有回音,提前感谢您的帮助
功能就像围墙花园——你可以进出,但当你在里面时,你看不到墙外的任何人。为了与代码的其余部分交互,您必须将结果传回,通过引用传入变量,或者(最糟糕的方式)使用全局变量。
您可以在函数内部将$errors数组声明为全局,然后对其进行更改。这种方法不需要我们从函数中返回任何内容。
function minLength($input, $min) {
global $errors;
if (strlen($input) <= $min) {
//this syntax adds a new element to an array
$errors[] = "Is that your real name? No its not.";
}
//else not needed. if input is correct, do nothing...
}
您可以通过引用传递$errors数组。这是另一种方法,允许在函数内部更改全局声明的变量。我推荐这种方式。
function minLength($input, $min, &$errors) { //notice the &
if (strlen($input) <= $min) {
$errors[] = "Is that your real name? No its not.";
}
}
//Then the function call changes to:
minLength($test, 20, $errors);
但为了完整性,以下是如何使用返回值来完成此操作。这很棘手,因为无论输入是否错误,它都会添加一个新的数组元素。我们并不真的想要一个充满空错误的数组,这毫无意义。它们不是错误,所以不应该返回任何内容。为了解决这个问题,我们重写函数以返回字符串或布尔值false,并在返回时测试值:
function minLength($input, $min) {
if (strlen($input) <= $min) {
return "Is that your real name? No it's not.";
} else {
return false;
}
}
//meanwhile, in the larger script...
//we need a variable here to 'catch' the returned value of the function
$result = minLength("12345678901234", 12);
if($result){ //if it has a value other than false, add a new error
$errors[] = $result;
}
minLength()
函数返回您定义的$errors
。但是,您的代码中没有$errors
接受该函数的返回。
示例代码为:
<?php
require_once("functions.php");
$errors = array();
$errors = minLength($test, 20);
if (count($errors) > 0) {
foreach($errors as $error) {
echo "<li>{$error}</li><br />";
}
} else {
echo "<p>No errors found </p>";
}
?>