普通网友 2013-03-11 01:35
浏览 9
已采纳

致命错误:调用成员函数准备非对象[重复]

This question already has an answer here:

Can somebody point me in the right direction as to why the following piece of code is failing..

MySQLDb.php:

class MySQLDb 
{
        protected $_mysql; 
        protected $_query;


        function __constructor($host,$username,$password,$db)
        {
            $this->_mysql = new mysqli($host,$username,$password,$db) or die('Problem connecting to the DB.');

        }


        function query($query)
        {
            $this->_query =  filter_var($query,FILTER_SANITIZE_STRING);
            $stmt = $this->_prepareQuery();
            $stmt->execute();
            $results = $stmt->_dynamicBindResult($stmt);
        }


 protected function _prepareQuery(){

            $dbh = $this->_mysql;
            if ( !$stmt = $dbh->prepare($this->_query) ) {
                trigger_error('Problem preparing query', E_USER_ERROR);

            }

            return $stmt;
        }

index.php:

require_once('MYSQLDb.php');

$Db = new MySQLDb('localhost','root','','blog');


$results =$Db->query("SELECT * FROM posts");

When I run the program it spits out the error fatal error: call to a member function prepare on a non-object at if ( !$stmt = $dbh->prepare($this->_query) ) {

I'm trying to learn the object oriented way of doing this things so not very clued in on how to troubleshoot this.

thanks.

</div>
  • 写回答

1条回答 默认 最新

  • duanqiao2225 2013-03-11 01:39
    关注

    The problem is in your constructor:

    function __constructor($host,$username,$password,$db) {
    

    The actual PHP "class constructor" name is __construct, not __constructor, so your version is never being called and $this->_mysql is null (i.e. - not an object).

    Try update the function to the following and it should work:

    function __construct($host,$username,$password,$db) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)