mehulmpt
mehulmpt

Reputation: 16547

How To Supply Constructor Argument To Other Methods In PHP?

I've following class:

class User {
    $con = mysqli_connect('localhost', 'root', '', 'thefilenet');

    public function __construct($username) {
        // code code code
    }

    public function isVerified($username) {
       $q1 = mysqli_query($con, "SELECT `Verified` FROM `_users` WHERE `Username` = '$username'");
        $verified = mysqli_fetch_array($q1)[0];
        return ($verified == 1) ? true : false;
    }

    public function thisThat($username) {
        // ...
    }
}

There are lots of methods as well which carry one same argument at least, $username supplied to constructor at the $user = new User('myUserName'); time. Now I want to use these methods without supplying $username argument everytime.

Like, I should be able to do $user->isVerified(); instead of $user->isVerified('myUserName');

How do I achieve this?

PS: $username argument is required in every method for dynamic table/record selection.

Upvotes: 0

Views: 23

Answers (1)

Oleg Dubas
Oleg Dubas

Reputation: 2348

Just save the $username you give to the constructor in a class private property for future use:

class User 
{
    private $username;

    function __construct($username) {
        $this->username = $username;
    }

    function isVerified() {
       // check $this->username
    }
}

Upvotes: 2

Related Questions