Switching Classes during __construct()

Let’s take the following classes for a moment:

class member {
    public $id;

    public function __construct($id) {
        $this->id = $id;

        // Check user level
        if ($this->check_user_level() == moderator) {
            $this = new moderator($this->id);
        }
    }

    private function check_user_level() {
        // Return user level from system based on user ID
    }
}

class moderator extends member {
    public function show_moderator_tools() {
        // etc.
    }
}

==================

$user = new member($user_id);

The desired behavior is to have $user detect whether the user is authorized to have moderator access, and if so recast the user using the moderator class instead of member.

PHP forbids simply reassigning $this, so what appears to be the best solution would be one of the following:

Run check_user_level($id) as a regular function and using an if statement

$user_level = check_user_level($id);

if ($user_level == "moderator") {
    $user = new moderator($id);
} else {
    $user = new member($id);
}

Set a flag in the base class that can be used for a check/redefinition after initializing $user

$user = new member($id);

if ($user->flag = TRUE) {
    $user = new moderator($id);
}

The latter feels like it’s introducing a security flaw, especially since the flag (which could just as easily be $user->user_level, or similar, I guess) would have to be public to be able to check it afterward.

What I would like to do would be to just make one call to new member($id) and have it handle things automatically from there, without the need for if statements after the fact. Is there a way to do this?


Source: oop

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.