我以面向对象的方式练习编码;尝试将一些经常使用的脚本用于表单处理并将其转换为函数。这是我的代码。
class FormHandler{
// Secure simple inputs
public function secure($var){
$var = stripslashes($var);
$var = strip_tags($var);
$var = htmlentities($var);
return $var;
}
public function getAll(){
foreach($_POST as $key => $value){
${$key} = secure($_POST[$key]);
}
$didGetAll =TRUE;
}
public function echoResults(){
if($didGetAll === TRUE){
echo "Form Contents<br>";
foreach($_POST as $key => $value){
echo $key." => ".${$key}."<br>";
}
}else{
echo 'do getAll() fuction first'."<br>";
}
}
}
当我运行这样的功能时:
include './formhandling.php';
$form = new FormHandler;
$form -> getAll();
$form -> echoResults();
它首先返回&#39; do getAll()函数&#39;消息即使$ didGetAll var应该= true。
我认为这是因为变量值不是在函数之间传递的?
我试图通过将$ didGetAll全局化并通过返回$ didGetAll来测试这一点。但它仍然会返回相同的结果。
有人可以建议我做错了吗?
答案 0 :(得分:2)
使用$didGetAll
作为类中的属性来访问对象。
class FormHandler{
private $didGetAll = FALSE;
// Secure simple inputs
public function secure($var){
$var = stripslashes($var);
$var = strip_tags($var);
$var = htmlentities($var);
return $var;
}
public function getAll(){
foreach($_POST as $key => $value){
$this->$key = $this->secure($_POST[$key]);
}
$this->didGetAll =TRUE;
}
public function echoResults(){
if($this->didGetAll === TRUE){
echo "Form Contents<br>";
foreach($_POST as $key => $value){
echo $key." => ".$this->$key."<br>";
}
}else{
echo 'do getAll() fuction first'."<br>";
}
}
}
答案 1 :(得分:0)
为此使用公共属性,它允许将数据存储在类中的变量中:
class FormHandler{
public $didGetAll = false;
// Secure simple inputs
public function secure($var){
$var = stripslashes($var);
$var = strip_tags($var);
$var = htmlentities($var);
return $var;
}
public function getAll(){
foreach($_POST as $key => $value){
${$key} = secure($_POST[$key]);
}
$this->didGetAll =TRUE;
}
public function echoResults(){
if($this->didGetAll === TRUE){
echo "Form Contents<br>";
foreach($_POST as $key => $value){
echo $key." => ".${$key}."<br>";
}
}else{
echo 'do getAll() fuction first'."<br>";
}
}
}
$form = new FormHandler;
$form -> getAll();
$form -> echoResults();
阅读this以了解它。