我刚开始编写PHP程序,我需要帮助解决什么是我确信是一个简单的问题。我试图在表单页面中添加一个名为“错误”的数组的值,这样我以后就可以回显它以进行验证,尽管我似乎无法从包含的函数文件中向数组添加任何内容。
我需要函数<?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>";
}
?>但是最后没有回音,谢谢你的帮助
发布于 2016-04-19 04:14:16
功能就像有围墙的花园--你可以进出,但是当你在里面的时候,你看不到墙外的任何人。为了与代码的其余部分进行交互,要么必须传回结果,通过引用传入变量,要么(最坏的方式)使用全局变量。
您可以在函数中将$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;
} 发布于 2016-04-19 04:08:07
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>";
}
?>https://stackoverflow.com/questions/36708097
复制相似问题