2011-07-20 41 views
0

你好,我只是堅持語法,任何人都可以幫我下一個代碼?類下的會話

class User {  
    protected $userID = preg_replace('#[^0-9]#i', '', $_SESSION['user_id']); 
    protected $useremail = preg_replace('#[^[email protected]_.-]#i', '', $_SESSION['user']); 
    protected $userPassword = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION['user_password']); 

    public function CheckUserLogin(){  
    if(!isset($_SESSION['user'])){ 
     header("location: login.php"); 
     exit();  
    } 

    //Try to find user from session data in database 
    $sql = "SELECT * FROM users WHERE id = '$this->userID' AND email = '$this->useremail' AND password = '$this->userPassword' LIMIT 1"; 
    $res = mysql_query($sql) or die(mysql_error()); 
    $userMatch = mysql_numrows($res); 
    if ($userMatch == 0) { 
     header("location: login.php"); 
     exit(); 
    } 
    } 
} 
+5

和什麼問題: – genesis

+0

解析錯誤:語法錯誤,意外 '(',希望 '' 或 ';' 在C:\ XAMPP \ htdocs中\社會\庫\用戶。 php on line 6 我不能做保護$ userPassword = preg_replace('#[^ A-Za-z0-9] #i','',$ _SESSION ['user_password']);我現在不是爲什麼 – Stefan

回答

4

首先,請注意,聲明屬性時,你不能分配給它,這不是知道在編譯時的值 - 這意味着你不能調用一個函數來初始化屬性。

此代碼:

protected $userID = preg_replace('#[^0-9]#i', '', $_SESSION['user_id']); 

無效。


作爲參考,你可以閱讀Properties頁的手冊(引述相關的句子):

They are defined by using one of the keywords public , protected , or private , followed by a normal variable declaration.

This declaration may include an initialization, but this initialization must be a constant value -- that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.


你應該先申報財產;以及後來(在你的類的constructor,例如),初始化:

class User { 

    protected $userID; 

    public function __construc() { 
     $this->userID = preg_replace('#[^0-9]#i', '', $_SESSION['user_id']); 
    } 
} 
+0

謝謝你mannnn這就是我需要的。 – Stefan

1

簡而言之:您只能分配常數表達式到類聲明中的屬性(類體內,但外面一個方法)。其他一切(變量,函數調用......)都被限制在代碼塊(主要函數和方法)中。

但是,你的代碼以你展示的方式是非常神奇的,你應該避免在任何情況下。使用構造函數,而不是

class User {  
    protected $userID; 
    protected $useremail; 
    protected $userPassword; 

    public function __construct ($userId, $user, $password) { 
    $this->userID = preg_replace('#[^0-9]#i', '', $userId); 
    $this->useremail = preg_replace('#[^[email protected]_.-]#i', '', $user); 
    $this->userPassword = preg_replace('#[^A-Za-z0-9]#i', '', $password); 
    } 

    // .. 
} 
+0

謝謝你我解決我的問題,這metod – Stefan