问题描述
我在PHP中使用PDO ...我遇到以下问题.
I am using PDO in PHP ... I have the following problem.
以下代码不起作用.
class A {
private $getUsersQuery = "SELECT * FROM users";
...
public function getUsers() {
$DBH = A::getDatabaseConnection();
try {
$query = $DBH->prepare($this->getUsersQuery);
...
} catch(PDOException $e) {}
}
}
但是如果我使用字符串,它就可以工作.
But if I use the string it works.
$DBH->prepare("SELECT * FROM users");
即使我在prepare()之外使用回显,它也可以工作...
Even if I use the echo outside the prepare() it works ...
echo $this->getUsersQuery; // Outputs the sql string.
有人可以指出问题所在吗?
Can someone point out what the problem might be.
更新:
错误:
SQLSTATE [42000]:语法错误或访问冲突:1065查询为空
SQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty
谢谢
推荐答案
如您的注释中所述,您对非静态方法进行了静态调用.
As mentionned in your comment, you make a static call to a method that is not static.
在这样调用的方法中使用$this
毫无意义:
Using $this
in a method that is called like this makes no sense:
$results = A::getUsers();
实例化您的类,然后在类对象上调用该方法.
Instanciate your class, and then call the method on the class object.
$a = new A();
$a->getUsers();
或将您的方法和SQL查询设为静态.
Or make your method and SQL query static.
这篇关于在PHP(PDO)中访问私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!