嘿伙计们我得到了这个错误:
Catchable fatal error: Argument 1 passed to Users::__construct() must be an instance of PDO, none given, called in C:\xampp\htdocs\xampp\ooplogin\register.php on line 46 and defined in C:\xampp\htdocs\xampp\ooplogin\class\Users.php on line 9
说真正的代码没有问题,但你知道如果我想制作干净的代码那么它应该是任何错误。
我的代码:
<?php
class Users {
/* Deklarovanie premennych */
public $name = null;
public $email = null;
public $phone = null;
public $message = null;
public function __construct(PDO $db_con)
{
$this->db_con = $db_con;
}
public function storeFormValues( $data )
{
if( isset( $data['name'] ) ) $this->name = stripslashes( strip_tags( $data['name'] ) );
if( isset( $data['email'] ) ) $this->email = stripslashes( strip_tags( $data['email'] ) );
if( isset( $data['phone'] ) ) $this->phone = stripslashes( strip_tags( $data['phone'] ) );
if( isset( $data['message'] ) ) $this->message = stripslashes( strip_tags( $data['message'] ) );
return $this;
}
public function message()
{
$correct = false;
try {
$sql = "INSERT INTO user(name, email, phone, message) VALUES (:name, :email, :phone, :message)";
$stmt = $this->db_con->prepare( $sql );
$stmt->bindValue( "name", $this->name, PDO::PARAM_STR );
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->bindValue( "phone", $this->phone, PDO::PARAM_STR );
$stmt->bindValue( "message", $this->message, PDO::PARAM_STR );
$stmt->execute();
return 'Sprava bola uspesne odoslana!';
}catch( PDOException $e ) {
return $e->getMessage();
}
}
public function displayAll()
{
try{
$sql = "SELECT * FROM users LIMIT 10";
$stmt = $this->db_con->prepare($sql);
$stmt->execute();
return $this->$stmt;
}catch( PDOException $e ) {
return $e->getMessage();
}
}
}
try {
$db_con = new PDO( DB_HOST, DB_USER, DB_PASS );
$db_con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$db_con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch( PDOException $e ) {
return $e->getMessage();
}
$Users = new Users($db_con);
$Users->storeFormValues( $_POST );
echo $Users->message();
?>
我的Index.php看起来像:
<?php if( !(isset( $_POST['send'] ) ) ) { ?>
HTML FORM HERE
<?php
} else {
$Users = new Users;
$Users->storeFormValues( $_POST );
if( $Users->message() ) {
echo "Sprava bola úspešne odoslana";
} else {
echo "Sprava nebola odoslana";
}
}
?>
这是否有机会帮助我解决它或解释为什么它不起作用?谢谢!
答案 0 :(得分:1)
您没有像错误消息那样传递PDO实例。
$Users = new Users;
编辑: 首先,不要复制/粘贴代码并期望它能够正常工作。我会告诉你该怎么做,但不会给你任何代码。
在构造函数中创建带参数(没有默认值)的类时,必须传递参数才能使其工作。这就是您收到此错误的原因。我告诉你的那一行是错误抛出的地方。用户类需要PDO对象,但您没有传递任何内容。虽然你是在你的班级文件中做到的:
$Users = new Users($db_con);
您需要的cource也需要像在类文件中那样初始化$ db_con变量。
这将解决您的问题。我也有一些建议。
include
和require
函数,了解如何从其他文件中获取代码以应用1和2。这些是非常基本的建议。有更复杂但更好的方法来做同样的事情,比如自动加载和IoC容器。但是在开始编码时,为了您的理智,您可以将这些概念留待以后学习。 :)