gpt4 book ai didi

php - 如何使用继承来传递查询?

转载 作者:行者123 更新时间:2023-11-29 06:19:58 26 4
gpt4 key购买 nike

这是我的代码结构。我想知道,我该如何优化它?换句话说,如何只编写一次 INSERT 查询? (因为它对所有方法都是不变的)

class Main { // here is some code }

class Test extends Main{

private $post_id;

public function __construct($post_id, PDO $db)
{
$this->post_id = $post_id;
}

public function func1()
{
// connect to database
INSERT IGNORE INTO viewed (post_id, username)
VALUES ($this->post_id, $_SESSION['username']);

}

public function func2()
{
// connect to database
INSERT IGNORE INTO viewed (post_id, username)
VALUES ($this->post_id, $_SESSION['username']);

}

public function func3()
{
// connect to database
INSERT IGNORE INTO viewed (post_id, username)
VALUES ($this->post_id, $_SESSION['username']);

}

}

我可以在Main 类中编写那个INSERT 查询吗?或者我怎样才能防止重复代码? (我的意思是INSERT代码)

最佳答案

不确定您的想法,但考虑到您发布的代码:

class Main {
// ...
protected funtion foo() {
// connect to database
INSERT IGNORE INTO viewed (post_id, username)
VALUES ($this->post_id, $_SESSION['username']);
}
}

class Test extends Main {

public function func1()
{
// ...
$this->foo();
}

public function func2()
{
// ...
$this->foo();
}

public function func3()
{
// ...
$this->foo();
}
}

关于php - 如何使用继承来传递查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33846430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com