开发者

Static array declaration in php database class - incorrect syntax error?

I'm declaring a simple database class that includes an array of prepared statement, but for the life of me,开发者_JAVA百科 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?


You should not have quotes around the ? for your parameter. Also, you cannot declare the private static $statements as an array. Instead, you must initialize it in the constructor.

class Database {
    private static $users_table = "users";
    private static $statements;

    public function __construct() {
      $this->statements = array("username_available" => "SELECT COUNT(*) FROM " . self::$users_table . " WHERE Username='?'");
      // etc...
    }

}


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

class Database {
    private static $users_table = "users";
    private static $statements = null;
    public function __construct(){
        if(self::$statements === null){
            self::$statements = array("username_available" => "SELECT COUNT(*) FROM " . self::$users_table . " WHERE Username=?");
        }
    }
}

This code should work in your case. And as Michael said you should remove quotes around the question mark.


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:

private static $time = time(); # this will fail too. Value must be a literal value

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:

private static $statements = array("username_available" => "SELECT COUNT(*) FROM `users` WHERE Username=?");


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:

<?php
class Database {
    private static $users_table = "users";
    private static function statements() {
           return array("username_available" => 
                 "SELECT COUNT(*) FROM " . self::$users_table . " WHERE Username=?");
    }
}
?>

Working example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜