这是我第一个基于 Oops 概念的 PHP 项目。我正在尝试从数据库表中获取所有 Subject_details,但我看不出我在哪里犯了错误。
当我运行我的 index.php 页面时,我收到一条错误消息:
Catchable fatal error: Argument 1 passed to book_info::__construct() must be an instance of connection, none given, called in D:\xampp\htdocs\bookshop\result.php on line 6 and defined in D:\xampp\htdocs\bookshop\classes\book_info.php on line 17
这是我的代码片段:
连接.php
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of connection
*
* @author Ashutosh
*/
class connection {
//put your code here
private $host = 'localhost';
private $dbname = 'bookfinder_com';
private $username = 'bookfinde';
private $password ='4324dsfs';
public $con = '';
function __construct(){
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We\'re sorry but there was an error while trying to connect to the database';
file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
}
}
?>
book_info.php 类
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of account_info
*
* @author Ashutosh
*/
class book_info{
private $con;
public function __construct(connection $con) {
$this->con = $con->con;
}
function getSubjectInfo(){
$sub_info = $this->con->prepare("SELECT * FROM subjectdetails");
$sub_info->execute();
$results = $sub_info->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $key) {
$results->subject_name;
}
}
}
?>
索引.php
<?php
include_once 'classes/connection.php';
include_once 'classes/book_info.php';
$con = new connection();
$info = new book_info();
$info->getSubjectInfo();
echo $info;
print($info);
?>