开发者

Using a class within a class?

I built myself a MySQL class which I use in all my projects. I'm about to start a project that is heavily based on user accounts and I plan on building my own class for this aswell. The thing is, a lot of the methods in the user class will be MySQL queries and methods from the MySQL class.

For example, I have a method in my user class to update someone's password:

class user() {
    function updatePassword($usrName, $newPass)
    {
      开发者_JAVA百科  $con = mysql_connect('db_host', 'db_user', 'db_pass');
        $sql = "UPDATE users SET password = '$newPass' WHERE username = '$userName'";
        $res = mysql_query($sql, $con);
        if($res) return true;
        mysql_close($con);
    }
}

(I kind of rushed this so excuse any syntax errors :) )

As you can see that would use MySQL to update a users password, but without using my MySQL class, is this correct? I see no way in which I can use my MySQL class within my users class without it seeming dirty. Do I just use it the normal way like $DB = new DB();? That would mean including my mysql.class.php somewhere too...

I'm quite confused about this, so any help would be appreciated, thanks.


You should explore dependency injection (PHP example)


Yes you have to include the mysql.class.php in order to use the class. But this is similar as in Java, Python, etc. You have to specify what you use.

One way to make the class available in your user class would be to call the constructor with an instance of the DB class:

class User {
    private $_db;
    public function __construct($db) {
        $this->_db = $db;
    }

    public function updatePassword($usrName, $newPass) {
        // use $this->_db here
    }

}

and then:

require 'mysql.class.php'

$user = new User(new DB());
$user->updatePAssword('foo', 'bar');


Study up on extending a class. Or in other words, inheritance.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜