Xavier C.
Xavier C.

Reputation: 1817

PDO request within a class

Here is my class :

class ProfileLink {

    function profileLink(PDO $pdo, $string, $i=0)
    {
        if ($i!=0) {
            $link = $string . '-' . $i;
        } else {
            $link = $string;
        }
        $req = $pdo->prepare('SELECT link FROM users WHERE link = ?');
        $req->execute(array($link));
        $nb = $req->rowCount();
        $req->closeCursor();
        if ($nb > 0) {
            $i++;
            return profileLink($pdo, $string, $i);
        } else {
            return $link;
        }
    }

}

When I call the profileLink function from the class, it doesn't work, but if I call it outside the class, everything is ok. It might be a problem with the PDO, what do you think ?

require_once ('lib/profileLink.class.php');
$profileLink = new ProfileLink();
$link = $profileLink->profileLink($pdo, $string);

Upvotes: 0

Views: 54

Answers (2)

Mario A
Mario A

Reputation: 3363

2 Things:

here

 return profileLink($pdo, $string, $i);

you are missing a $this, because it's no regular function but a class method:

 return $this->profileLink($pdo, $string, $i);

And second, your method has the same name as the class (except of the first capital letter), and thus seems to be interpreted as constructor. I have just tested this:

class Test {
    function test() {
        echo "test";
    }
}
$t = new Test();

And it outputs "test".

So you should rename your method to getLink or something similar.

Upvotes: 0

Dave
Dave

Reputation: 3658

I would store the instance of PDO as a class property so that it can be easily accessed within the class. Note that my example uses slightly different syntax (modern PHP).

class ProfileLink {

    protected $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;  
    }

    public function profileLink($string, $i=0)
    {
        if ($i!=0) {
            $link = $string . '-' . $i;
        } else {
            $link = $string;
        }
        $req = $this->pdo->prepare('SELECT link FROM users WHERE link = ?');
        $req->execute(array($link));
        $nb = $req->rowCount();
        $req->closeCursor();
        if ($nb > 0) {
            $i++;
            return profileLink($string, $i);
        } else {
            return $link;
        }
    }

}
$profileLink = new ProfileLink($pdo);

Upvotes: 1

Related Questions