2

I have a connection.php class, which is just here for the connection string to my MySQL database using the PDO object.

Then, I call the connection.php class in a query.php page, but when I try to get the PDO object from connection.php, I get an error "Expression is not allowed as field default value". (btw, my IDE is phpstorm)

Here is connection.php

class connection
{
    private $host = "XXX";
    private $db = "XXX";
    private $login = "XXX";
    private $password = "XXX";

        public function conn()
        {
            try
            {
                $bddconn = new PDO('mysql:host='.$this->host.';dbname='.$this->db, $this->login, $this->password);
            }
            catch(PDOException $e)
            {
                echo "Connection failed " . $e->getMessage();
            }
            return $bddconn;
        }
}

And here is query.php

class query extends connection
{
    public $bdd = parent::conn();

    public function checkUser($login, $password)
    {
        $query = 'SELECT login, password FROM user WHERE login = ? AND password = ?;';
        $req = $this->bdd->prepare($query);
        return $req->execute(array($login, $password));
    }
}

However, at this point the IDE displays the error "Expression is not allowed as field default value" on query.php line 2 (public $bdd = parent::conn();)

What is the problem on my code?

  • 1
    It's what it says, you can't have expressions (parent::conn() is an expression) as a default property value. Call it in `__construct` instead. – Jonnix Jan 29 '19 at 08:56
  • ....have you tried googling that error message? If any is given, link in your case, that is mostly helpful ;) – Nico Haase Jan 29 '19 at 09:03
  • Possible duplicate of [Expression is not allowed as field default value](https://stackoverflow.com/questions/35037368/expression-is-not-allowed-as-field-default-value) – Nico Haase Jan 29 '19 at 09:03

1 Answers1

7
public $bdd = parent::conn();

You can't set property value from a function in the property declaration

You must initialize property value in methods, for example in constructor

class query extends connection
{
    public $bdd;

    public function __construct()
    {
        parent::__construct();
        $this->bdd = parent::conn();
    }
}
Maksym Fedorov
  • 6,383
  • 2
  • 11
  • 31