【发布时间】:2017-12-06 10:27:39
【问题描述】:
我正在研究 php 并试图自己将它与 oop 集成,谁能解释这个错误的想法?
我猜它找不到查询,但我不明白为什么,因为在 $query 中一切都是正确的,p.s global $mysqli 仅用于测试目的,我知道不小心使用它是不好的。
<?php
class Index{
public function connect(){
$mysqli=new mysqli();
$mysqli->connect('localhost',"root","");
$conn=$mysqli->select_db("webartisan");
if($mysqli->errno){
echo "Unable to connect to the database: ".$mysqli->error;
exit();
}
}
public function select_data($table,$id){
$query="SELECT * FROM {$table} WHERE id=$id ";
}
public function insert_data(){
global $conn;
$username=$_POST['username'];
$password=$_POST['password'];
$query="INSERT INTO artisan(username,password) VALUES('$username','$password')";
$result=$conn->query($query);
if($result->num_rows){
return true;
}
}
public function register(){
if(isset($_POST['submit'])){
self::insert_data();
}
}
}
$index=new Index();
$index->register();
?>
<form method="POST" action="index.php">
<input type="text" name="username"><br><br>
<input type="password" name="password"><br><br>
<input type="submit" name="submit">
</form>
错误:
致命错误:未捕获的错误:在 null 上调用成员函数 query() 在 C:\xampp\htdocs\webartisan\index.php:23 堆栈跟踪:#0 C:\xampp\htdocs\webartisan\index.php(31): 索引->insert_data() #1 C:\xampp\htdocs\webartisan\index.php(36): Index->register() #2 {main} 在第 23 行的 C:\xampp\htdocs\webartisan\index.php 中抛出
【问题讨论】:
-
如果你想在一个类的方法之间共享变量,那么
$conn应该是$this->conn,这意味着你可以去掉global $conn -
但是 $conn 在函数内部,所以我应该找到其他方法吗?
-
您的函数被包装在类中,它们的行为与您所期望的略有不同。将
self::insert_data();更改为$this->insert_data();,因为不需要静态调用。我不确定你在哪里打电话给connect()。 -
我应该找到其他方法吗? @Scuzzy 给了你正确的方向...摆脱
global任何你可以...代码OOP跨度> -
现在 $conn 未定义,我调用了 connect() 但仍然未定义
标签: php