VARIABLE, expecting T

I am expecting this to be a basic syntax error I overlooked, but I can't figure it out.

In a PHP script, I keep getting the following error.

Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in [path]/scripts/users/database_connection.php on line 4

This occurs when my script to connect to the database is called with an include_once() . I stripped my script down to the most basic code (leaving in what is required by other code), and it still is calling this error.

<?php
    class UserDatabaseConnection
    {
        $connection = sqlite_open("[path]/data/users.sqlite", 0666);
        public function lookupUser($username)
        {
            // rest of my code...
        }
    }

    $udb = new UserDatabaseConnection;
?>

I have struggled with this for a while, and just wondered if anyone else could spot somewhere I went wrong.


You can not put

$connection = sqlite_open("[path]/data/users.sqlite", 0666);

outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.


You cannot use function calls in a class construction, you should initialize that value in the constructor function.

From the PHP Manual on class properties:

This declaration may include an initialization, but this initialization must be a constant value --that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

A working code sample:

<?php
    class UserDatabaseConnection
    {
        public $connection;
        public function __construct()
        {
            $this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
        }
        public function lookupUser($username)
        {
            // rest of my code...
            // example usage (procedural way):
            $query = sqlite_exec($this->connection, "SELECT ...", $error);
            // object oriented way:
            $query = $this->connection->queryExec("SELECT ...", $error);
        }
    }

    $udb = new UserDatabaseConnection;
?>

Depending on your needs, protected or private might be a better choice for $connection . That protects you from accidentally closing or messing with the connection.


Use access modifier before the member definition:

    private $connection;

As you cannot use function call in member definition in PHP, do it in constructor:

 public function __construct() {
      $this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
 }
链接地址: http://www.djcxy.com/p/9960.html

上一篇: “意外的标记非法”没有可见的原因

下一篇: VARIABLE,期待T