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

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

报告相同问题?