我正在使用 MySQLi 创建一些基本的 OO 脚本,并在使用 stmt_init()、prepare() 或 query() 中的任何一个时出现未定义的方法错误……同时在 connect_errno() 中也出现错误。我确实知道在我的 php.ini 中启用了 mysqli 扩展(未注释),并且 phpinfo() 同时启用了 mysqli 和 mysqlnd ...所以不知道为什么我无法访问方法/属性。我得到的错误是:致命错误:调用未定义的方法 mysqli::connect_error()
class db {
public $host = 'localhost';
public $username = 'root';
public $password = '';
public $database = 'molecule';
public $mysqli = '';
function __construct() {
$this->mysqli = new mysqli($this->host, $this->username, $this->password, $this->database);
return $this->mysqli;
}
}
class nodeModel {
function __construct() {
$this->mysqli = new db;
if($this->mysqli->connect_error()){ printf("Database Connection failed: %s\n", $this->mysqli->connect_error()); }
}
function insertNode() {
$this->insert = $this->mysqli->stmt_init();
$this->insert->prepare("INSERT INTO node(node_name, node_link, node_comment) VALUES (?, ?, ?)");
$this->insert->bind_param($this->node_name, $this->node_link, $this->node_comment);
if($this->insert->execute()) {
$this->insert_id = $this->mysqli->insert_id;
}
$this->insert->close();
print_r($this->insert_id);
return $this->insert_id;
}
所以,要让 insertNode() 方法工作......这些是我放在 nodeModel 类中的其他方法
public function setNodeName($value) { $this->nodeName = $value; }
public function setNodeLink($value) { $this->nodeLink = $value; }
public function setNodeComment($value) { $this->nodeComment = $value; }
public function getNodeName() { return $this->nodeName; }
public function getNodeLink() { return $this->nodeLink; }
public function getNodeComment() { return $this->nodeComment; }
public $insert_id;
function insertNode($nodeName, $nodeLink, $nodeComment) {
$this->mysqli->stmt_init();
$this->mysqli->prepare("INSERT INTO node(node_name, node_link, node_comment) VALUES (?, ?, ?)");
$this->mysqli->bind_param($this->node_name, $this->node_link, $this->node_comment);
if($this->mysqli->execute()) {
$this->insert_id = $this->mysqli->insert_id;
}
$this->mysqli->close();
print_r($this->insert_id);
return $this->insert_id;
}
如何将变量传递给方法?我正在尝试这个...
$connect = new db();
$db = new nodeModel($connect);
$db->setNodeName('My Node Title');
$db->setNodeLink('My Node Link');
$db->setNodeComment('My Node Comment. This one should be longer so I will write more stuff');
$db->insertNode($db->getNodeName(), $db->getNodeLink(), $db->getNodeComment());
但这行不通。我的困惑实际上是关于类方法内部的 OO 范围......我不确定我应该传递什么。