2011-07-14 54 views
0
require_once('classes/class.validation.php'); 

$array = $_POST['array']; 
$pass_profanity = false; 
$validation = new Validation; 
function check_for_profanity($input){ 
    if(is_array($input)){ 
     foreach($input as $row){ 
      if(is_array($row)){ 
       check_for_profanity($input); 
      } else { 
       $pass_profanity = $validation->check_for_profanity($row); 
      } 
     } 
    } else { 
     $pass_profanity = $validation->check_for_profanity($input); 
     return; 
    } 
    return; 
} 
check_for_profanity($array); 

但我得到的錯誤:PHP變量的作用域幫助

Notice: Undefined variable: validation in /Library/WebServer/Documents/file.php on line 22

Fatal error: Call to a member function check_for_profanity() on a non-object in /Library/WebServer/Documents/file.php on line 2

我不出來,有什麼想法???

在此先感謝!

+0

在你的函數check_for_profanity中定義'$ validation'。 – Josh

回答

2

您可以訪問該變量在功能與global

function check_for_profanity($input){ 
    global $validation; 
    ... 
} 

或者,更好的方式是通過檢索它參數:

function check_for_profanity($input, $validation){ 
    ... 
} 

check_for_profanity($array, $validation); 

R ead the PHP manual - variable scope for more information

+0

@FraserK你從Sascha的答案中選擇了兩種方法中的哪一種? –

1

您正在定義$ validation = new Validation;功能之外。因此PHP不知道它存在。

1

使用global關鍵字:PHP.net: Variable Scope

$validation = new Validation; 
function check_for_profanity($input){ 

    global $validation; 

    //The rest of your function 
} 
+0

因爲這是一個遞歸函數,如果它被聲明爲全局函數,它是否會損害系統內存? – FraserK

+0

@FraserK老實說,我不知道。據我所知,全局關鍵字本質上是引用'$ GLOBALS'數組。函數的遞歸性質不應該產生影響,因爲每次調用global關鍵字都會導致應用程序不斷引用同一個對象。但是,我不知道這是一個事實。 –

+0

好吧:)我剛剛意識到,遞歸的水平不會深入反正:)所以它應該沒問題 – FraserK