"mysqli_connect" does not work

Asked

Viewed 369 times

2

I am unable to use the "mysqli_connect" function. Can anyone help me? You are returning the following error:

Fatal error: Constant Expression contains invalid Operations in /home/Vagrant/Projetos/products/app/Database/Connection.php on line 11

This is my code:

<?php

namespace App\Database\Connection;

class Connection
{
   protected $host = '127.0.0.1';
   protected $user = 'homestead';
   protected $password = 'secret';
   protected $database = 'products_crud';
   protected $connection = mysqli_connect($this->host, $this->user, $this->password, $this->database);  
}

The error happens in this line of code:

protected $connection = mysqli_connect($this->host, $this->user, $this->password, $this->database);

1 answer

2

I believe that to do what you want you should use the __construct(), that way when you do the new Connection(), for example, you will automatically trigger the construct(), he is able to set the variable as desired.

For example:

namespace App\Database\Connection;

class Connection
{
    protected $host = '127.0.0.1';
    protected $user = 'homestead';
    protected $password = 'secret';
    protected $database = 'products_crud';
    protected $connection;

    function __construct(){
        $this->connection = mysqli_connect($this->host, $this->user, $this->password, $this->database);
    }
}

You can see what is supported here, only some examples of what you can’t do, briefly, (at least not in version 7.1):

protected $ip = $_SERVER['REMOTE_ADDR'];
// Definir o $ip com base em uma variável "run-time".

protected $enviar = function($email){
 //...
}
// Utilizar o $enviar como uma função.

protected $calculo = bcadd('10', '20');
// Definir o $calculo com base na execução de uma função (isto foi o que você fez).

Well, there’s a lot more you can’t do, but it’s easier see here what is allowed to do. ;)

Browser other questions tagged

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