【问题标题】:PDO request within a class类内的 PDO 请求
【发布时间】:2015-02-20 19:45:12
【问题描述】:

这是我的课:

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;
        }
    }

}

当我从类中调用 profileLink 函数时,它不起作用,但如果我在类外调用它,一切正常。这可能是 PDO 的问题,您怎么看?

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

【问题讨论】:

    标签: php class pdo


    【解决方案1】:

    我会将 PDO 的实例存储为类属性,以便可以在类中轻松访问它。请注意,我的示例使用的语法略有不同(现代 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);
    

    【讨论】:

    • 感谢 Dave,您存储 PDO 的方式对我来说是完美的!
    • 您还可以围绕 PDO 创建一个包装器。一个很好的例子是通过 Aura\SQL 的 ExtendedPDO。链接here.
    【解决方案2】:

    两件事:

    这里

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

    您缺少$this,因为它不是常规函数而是类方法:

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

    其次,您的方法与类同名(第一个大写字母除外),因此似乎被解释为构造函数。我刚刚测试了这个:

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

    它输出"test"

    因此,您应该将方法重命名为 getLink 或类似名称。

    【讨论】:

    • 感谢您的发言马里奥,我会尽量遵守这些规则。但是 profileLink($pdo, $string, $i);或 $this->profileLink($pdo, $string, $i);为我返回相同的结果。
    • 真的吗?我收到一个致命错误。我假设您的代码永远不会到达函数调用。
    猜你喜欢
    • 2013-09-07
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2011-11-19
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多