开发者

Session under class

Hello i just stuck in syntax, can anyone help me with next code?

class User {    
  protected $userID = preg_replace('#[^0-9]#i', '', $_SESSION['user_id']);
  protected $useremail = preg_replace('#[^A-Za-z0-9@_.-]#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();
    }开发者_运维问答
  }
}


First of all, note that when declaring a property, you cannot assign it a value that's not know at compile-time -- which means you cannot call a function to initialize a property.

This code :

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

Is not valid.


As a reference, you can read the Properties page of the manual (quoting the relevant sentence) :

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.


You should first declare the property ; and, later (in the constructor of your class, for instance), initialize it :

class User {

    protected $userID;

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


In short: You can only assign constant expressions to properties within the class declaration (within the class body, but outside a method). Everything else (variables, function calls, ...) are restricted to code blocks (main, functions and methods).

However, your code in the way you show it is very magic, what you should avoid in any case. Use the constructor instead

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('#[^A-Za-z0-9@_.-]#i', '', $user);
    $this->userPassword = preg_replace('#[^A-Za-z0-9]#i', '', $password);
  }

  // ..
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜