January 2, 200917 yr Hey, I'm in the process of building a social network website and am building the user system. However, I've come across a bit of an obstacle. On every page requiring user interaction I define the user class. $user = new user(); In this case, the class searches the PHP session and looks for the users id, if found it then populates the class with the users information. $user = new user(235); In this case, the class simply populates the class with the information of the user with id "235". class user { var $type; var $userid; var $username; var $password; var $email; var $status; var $about; var $activation; function user($userid = false) { if($userid == false) { if(!empty($_SESSION['cn_userid'])) { $this->setUserid($_SESSION['cn_userid']); $this->setType(0); } else { return false; } } else { $this->setUserid($userid); $this->setType(1); } $query = mysql_query("SELECT * FROM users WHERE id = '".$this->getUserid()."' LIMIT 1"); if (mysql_num_rows($query) > 0) { $result = mysql_fetch_array($query); $this->setUsername($result['username']); $this->setEmail($result['email']); $this->setStatus($result['status']); $this->setAbout($result['about']); $this->setActivation($result['activation']); return true; } else { return false; } } //Rest of class snipped } However, I need to capture the output of the constructor (it returns false when the user isn't found). I have tried the following: $user = new user(); if(!$user) { blah blah } but this doesn't work as the variable isnt stored. Any help is appreciated. Dan
January 2, 200917 yr A constructor is not designed to return a value. It really isn't the same as any other member function, and in other languages the constructor is the only method on a class not be declared with a return type ("void" must be explicitly used for all other functions which do not return a value, but is illegal for a constructor). Instead, a constructor is used to initialise a new object. The result of the "new X()" operation is to create a new instance and set the LHS to reference the new object---any value returned by the constructor here is ignored. So your constructor should not return anything. When you do if(!$user), you're actually checking to see if the $user variable is NULL, which it will never be given you just assigned it to a new instance. A workaround is to delete the same instance using unset($this) in the constructor. However, this is really bad programming practise, and totally unobvious. You should instead use some other flag and method on your class. For example, an "exists" flag which can be set to true or false in the constructor. Then you can check the state of this flag using if(!$this->exists).
Create an account or sign in to comment