"mysqli_connect" does not work

2

I can not use the "mysqli_connect" function. Can someone help me? You are returning the following error:

  

Fatal error: Constant expression contains invalid operations in   /home/vagrant/Projects/products/app/Database/Connection.php on line 11

My code is this:

<?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);
    
asked by anonymous 06.05.2017 / 17:00

1 answer

2

I believe that in order to do what you want you should use __construct() , in this way When you do new Connection() , for example, you will automatically trigger construct() , it is able to set the variable as you want.

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 , just some examples than you < can not , 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 not do, but it's easier to see what's allowed to do here. ;)

    
06.05.2017 / 17:37