PHP数据库类中的静态数组声明 - 不正确的语法错误?
我正在声明一个简单的数据库类,其中包含一组准备好的语句,但是对于我来说,我在这里找不到语法错误。
class Database {
private static $users_table = "users";
private static $statements = array("username_available" => "SELECT COUNT(*) FROM " . self::$users_table . " WHERE Username='?'");
}
这里有什么帮助吗?
I'm declaring a simple database class that includes an array of prepared statement, but for the life of me, I can't find the syntax error here.
class Database {
private static $users_table = "users";
private static $statements = array("username_available" => "SELECT COUNT(*) FROM " . self::$users_table . " WHERE Username='?'");
}
Any help here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的参数的
?
不应包含引号。另外,您不能将private static $statements
声明为数组。相反,您必须在构造函数中对其进行初始化。You should not have quotes around the
?
for your parameter. Also, you cannot declare theprivate static $statements
as an array. Instead, you must initialize it in the constructor.在类变量声明上赋值时不能连接:您可以只分配一个标量值或另一个数组(或者一个对象,如果我没记错的话)。
您可以将表达式分配给方法,例如类构造函数,或者可能是另一个静态方法。
此代码应该适用于您的情况。正如迈克尔所说,你应该删除问号周围的引号。
you cannot concatenate while assigning values on class variables declaration: you can assign just a scalar value or another array (or an object if I remember correctly).
You can assign expressions into a method, like the class constructor, or maybe another static method
This code should work in your case. And as Michael said you should remove quotes around the question mark.
我不认为 PHP 喜欢从连接中声明静态类变量,否则需要评估。您也不能将静态变量设置为函数调用的结果:
换句话说,类定义中的属性值不能来自计算的内容。
因此,您必须将
$users_table
字符串的值硬编码到$statements
中:I don't think PHP likes declaring static class variables from concatenations or otherwise requires evaluation. You can't set a static variable to the result of a function call either:
In other words, a propety values in a class definition can't come from something that's evaluated.
So you have to hardcode the value of the
$users_table
string into the$statements
:由于在设置类属性时需要进行评估,您遇到了问题。
这是因为 PHP 类属性 " 必须能够在编译时评估,并且不得依赖于运行时信息来评估。”。请参阅先前链接页面上的示例。
要保持相同的格式,您可以使用一个静态方法,它只返回您想要的值:
正在工作示例
You're having problems due to requiring an evaluation when setting a class property.
This is because a PHP class property, "must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.". See the examples on the previously linked page.
To keep the same format you could just have a static method, that simply returns the value you want:
Working example