PDO中的错误:在null上调用成员函数prepare() [英] ERROR in PDO : Call to a member function prepare() on null

查看:75
本文介绍了PDO中的错误:在null上调用成员函数prepare()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对prepare函数有问题==>在null上调用成员函数prepare() 我有两个页面 classo.php index.php

I have a problem with prepare function ==> Call to a member function prepare() on null i have tow pages classo.php and index.php

classo.php:

classo.php :

    <?php 

        class classo
        {

            function connection(){

                $db=new pdo ('mysql:host=localhost;dbname=pronostic','root','');
                $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);

            }



            function insererDonne($pseudo,$password)
            {      
                        global $db;
                        classo::connection();     
                $donne=array(
                    'user' =>$pseudo,
                    'pass' =>$password 
                    );

                $req="INSERT INTO users (user,pass) VALUES (:user,:pass)";

                $sql=$db->prepare($req);

                $sql->execute($donne);

            }



        }


 ?>

index.php:

index.php:

<?php 


require('classo.php');


$data=new classo();
$data->insererDonne('dsds','tosdsta');


 ?>

您对我如何解决此问题有想法吗?这是我第一次从PHP收到此错误,并且我对PHP中的对象&是一种新的编码方式.类.有人可以帮我解决这个问题吗?

Do you have an idea as to how I can resolve this? This is the first time I've received this error from PHP and I'm kind of new coding in PHP with objects & classes. Could someone help me fix this problem please?

推荐答案

您的代码中有2个大问题:

There are 2 big issues in your code:

  1. 可见度可变
  2. 静态通话

详细信息:

  1. 在操作中,您应该忘记全局变量.它们违反封装原理.而且,您的代码中甚至没有任何全局变量,因此global $db;行是没有意义的.在类级别声明一个私有$ db变量(属性)在以下位置对其进行初始化connection()方法并在insert方法中访问它.

  1. In oop you should forget about global variables. They are against the principle of encapsulation. Moreover, you do not even have any global variable in your code, so global $db; line is meaningless. Declare a private $db variable on class level (property) initialise it in the connection() method and access it in the insert method.

您将连接方法称为classo::connection();.但是,您需要将连接方法声明为静态.可以将连接方法声明为静态(但也可以将$ db更改为静态),也可以使用$ this将其作为常规方法调用.

You are calling the connection method as classo::connection();. However, you would need to declare connection method as static. Either declare your connection method as static (but then change $db into static as well), or call it as a regular method using $this.

这篇关于PDO中的错误:在null上调用成员函数prepare()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆