开发者

Overriding a PHP __construct

I'm currently using a constructor in my PHP class to check whether a user is logged in or not. The constructor calls a function to check if they have a session ID, etc. - and if they don't it redirects them to a login page. Here's an idea of what I'm using:

function __construct() {
   parent::__constru开发者_Python百科ct();
   $this->check();
   $this->mid = $this->session->userdata('member_id');
}

function check() {
   if($this->mid == ''){
      $this->login();
   }
}

function signup() {
   // registration code
}

This constructor, of course, runs before every other function in the class. However I have a registration function that needs users not to be logged in when they access it. Is there any way of making an exception or overriding the __construct function so that not-logged-in users can access the registration function?


You need to redesign your code. First you define a class which ALWAYS does something (validation of users), then you want to use that class for users which don't have that something (not validated users); to avoid a total hack, you should refactor your code, not look for a patch that will allow you to work around the restriction you placed upon your class.


I have a simple guideline when designing classes: no functionality in constructor(only stuff that initializes something)

If this is absolutely needed in this case, put an if that checks if user is logged in, like a call like if(User::logged_in()) { .. }


__construct is automatically called on object creation, there's no way to change it. However, if you extend the class in question and write __construct function for that derived class, it would be called first, and you can do anything you want there and then call parent constructor via parent::__construct(); as in your example. Be advised though doing stuff to objects without constructor being called is usually not the best idea, so I'd advise to refactor the code so that logic is taken outside of the constructors as much as possible. Then also overriding stuff will be easier.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜