Syntax error - parse_url(getenv("CLEARDB_DATABASE_URL"));

Asked

Viewed 114 times

1

I’m trying to connect the database of a PHP application to herokuapp using Cleardb and simply getting a syntax error on line 6 of the code and I don’t know exactly why. The application does not work, only if I put host, password and username directly, which is not possible because the application is in the git also.

Follows the code:

    <?php

class Database {

    private $url = parse_url(getenv("CLEARDB_DATABASE_URL"));
    private $host = $url["host"];
    private $db_name = substr($url["path"], 1);
    private $username = $url["user"];
    private $password = $url["pass"];
    public $conn;

    public function getConnection() { 

            $this->conn = null;

            try {
                $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            } catch (PDOException $exception) {
                echo "Connection error: " . $exception->getMessage();
            }

            return $this->conn;
    }     
}

?>
  • Which error appears?

  • This one "Parse error: syntax error, Unexpected '(', expecting ',' or ';' on line 6" ...

1 answer

0


Object properties should be instances with simple values defined at compile time and not determined at runtime as function calls and other types of expressions.

class Database {
   private $url = parse_url(getenv("CLEARDB_DATABASE_URL"));

Play this initialization in the class constructor:

public function __construct(){
    $this->url =  parse_url(getenv("CLEARDB_DATABASE_URL"));
    $this->host = $this->url["host"];
    $this->db_name = substr($this->url["path"], 1);
    $this->username = $this->url["user"];
    $this->password = $this->url["pass"];
}

Property - Manual

  • hmmmmmm...got, but now I get the following error: "Parse error: syntax error, Unexpected '$url' (T_VARIABLE) " ...

  • @Lucasdealbuquerque this applies to the others too, I made an edition in the reply.

  • Hmmmmmm...that’s right, perfect! Now spun smooth...thank you so much for the help...! Something so simple and I breaking my head... --'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.