2012-05-01 52 views
-3

不知道更好的標題,但這是我的代碼。在php中使用undefined常量

我時,它的實例化,檢查形式的數據類用戶,但我得到下面的錯誤/通知:

Notice: Use of undefined constant username - assumed 'username' in C:\Users\Jinxed\Desktop\WebTrgovina\app\m\Register\User.m.php on line 7 

Notice: Use of undefined constant password - assumed 'password' in C:\Users\Jinxed\Desktop\WebTrgovina\app\m\Register\User.m.php on line 7 

Notice: Use of undefined constant passwordc - assumed 'passwordc' in C:\Users\Jinxed\Desktop\WebTrgovina\app\m\Register\User.m.php on line 7 

... and so on for every defined variable in user class. 

這裏的用戶等級:

class User { 
    function __construct(){ 
     $test = 'blah'; 
     $username; $password; $passwordc; $name; $surname; $address; 
     $this->checkInput(array(username=>20, password=>20, passwordc=>20, name=>20, surname=>40, address=>40)); 
    } 
    //array(formName=>CharacterLimit) 
    private function checkInput($fields){ 
     foreach($fields as $field=>$limit){ 
      if($_POST[$field]=='' || strlen($_POST[$field])>$limit) $this->error[] = "$field must be filled in, and it must be less than or $limit characters long."; 
      else $this->{$field} = $_POST[$field]; 
     } 
    } 
} 

我不太明白什麼是問題,我試着先創建變量,然後從主程序調用checkInput方法,但我得到同樣的錯誤。

+0

可能重複: //stackoverflow.com/questions/748289/php-getting-a-use-of-undefined-constant-cookie-login-how-do-i-fix-this。請求重複之前請使用搜索功能。 – Gordon

+1

http://stackoverflow.com/questions/2941169/what-does-the-php-error-message-notice-use-of-undefined-constant-mean/8025500#8025500 – Gordon

回答

7

你應該引用的是你作爲數組鍵使用字符串:

$this->checkInput(array(
    'username'=>20, 
    'password'=>20, 
    'passwordc'=>20, 
    'name'=>20, 
    'surname'=>40, 
    'address'=>40)); 

documentation說:

If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first define() bar as a constant).

相關部分的一半的權利,例如HTTP的
+0

可能的重複你是什麼意思?這:'$ _POST [「$ field」]'或這個'else $ this - >「$ field」= $ _POST [$ field];'因爲我試過最後一個,我得到這個錯誤:'Parse錯誤:語法錯誤,意外的''',期望T_STRING或T_VARIABLE或者第12行中的C:\ Users \ Jinxed \ Desktop \ WebTrgovina \ app \ m \ Register \ User.m.php中的'{'或'$'。 – Jinx

+0

@Jinx:完成編輯,再看一下,當然你不會通過修改第12行來修復第7行出現的錯誤。 – Jon

+0

啊..好吧,謝謝,我現在明白了,我看到了幾個例子,使用 – Jinx