2

可能重复:
致命错误:在非对象上调用成员函数 query()

我有一个类文件,我们称它为“东西”

Stuff.class

里面有一堂课

class  Stuff {

在那里我有一个公共静态函数

   public static function morestuff() {

}

在里面我需要调用另一个函数进行查询

$q="Select from contacts where id =". $this->$db->escapeVal($ID)".";

但我得到错误。

$q="Select from contacts where id =". escapeVal($ID)".";

退货

Call to undefined function escapeVal()


$q="Select from contacts where id =". $db->escapeVal($ID)".";

退货

Call to a member function escapeVal() on a non-object


$q="Select from contacts where id =". $this->$db->escapeVal($ID)".";

退货

Using $this when not in object context 

那我放什么呢?

编辑:

同一文件中的类似函数具有以下代码

'id' = '" . $this->db->escapeVal($this->_Id) . "'

但是,当我尝试在我的 mysql 查询中使用此代码时,我收到以下错误

Using $this when not in object context
4

4 回答 4

0
$Stuff->db->escapeVal($id)

开始工作。很高兴我让它工作,非常感谢你。

于 2012-07-09T20:38:16.913 回答
0

您不了解 OOP 的概念。$this是一个引用当前对象(或此对象)的变量。意义:

class Test {
    public function __construct() { //Called when object is instantiated
        var_dump($this);
    }
}
$test = new Test();

你会得到类似的东西

object(Test)#1 (0) { }

您不能$this在类方法之外使用。它只是不那样工作。

关于您遇到的错误,请尝试找出数据库连接存储在哪里。该连接应该传递给对象以存储为字段,或者直接传递给方法以在内部使用它。

编程不是复制/粘贴有效的代码。

于 2012-07-09T19:38:41.573 回答
0

因为您的函数是静态的,所以变量$this不会存在于其中。

要解决您的问题,有两种解决方案:

  1. 制作$db一个静态变量,这意味着它在每个实例中都是相同的。
  2. 从函数中删除static关键字morestuff()。在这种情况下,您需要创建该类的实例才能调用morestuff().
于 2012-07-09T19:39:08.427 回答
0

我怀疑这$db是一个全局变量,所以试试

public static function morestuff() {
      global $db;

      $q="Select from contacts where id =". $db->escapeVal($ID);

}

如果函数在同一个类中并且也是静态的,你会这样称呼它

self::escapeVal($ID);
于 2012-07-09T19:27:04.653 回答