Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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::__construct();
   $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?

like image 649
hohner Avatar asked Mar 12 '26 16:03

hohner


2 Answers

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.

like image 147
Paul Sonier Avatar answered Mar 15 '26 06:03

Paul Sonier


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()) { .. }

like image 36
Smar Avatar answered Mar 15 '26 04:03

Smar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!