droos02800 2017-06-16 12:39
浏览 42
已采纳

在PHP中跨函数共享变量值

I'm practising coding in an object oriented way; experimenting with taking some frequently used scripts for form handling and turning them into functions. Here is my code.

    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>";
                }
    }
    } 

When I run the functions like so:

include './formhandling.php';

$form = new FormHandler;
$form -> getAll();
$form -> echoResults();

it returns the 'do getAll() fuction first' message even though the $didGetAll var should = true.

I assume this is because the variable values aren't being passed between functions?

I've tried to test this by making $didGetAll global, and by doing return $didGetAll. But it still returns the same result.

Could someone suggest what I'm doing wrong?

  • 写回答

2条回答 默认 最新

  • douye9822 2017-06-16 12:42
    关注

    Use $didGetAll as a property in your class to access in object.

    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条)

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧