0

I have a problem with classes in PHP, I want to assign values received from the database to a private variable so that I can then use them in class functions. But in doing so I get the error:

Fatal error: Constant expression contains invalid operations in ..\database.php on line 21

Here is my code:

class Ustawienia {
    private $current_id = $_SESSION['user_id'];

    private $uprawnienia = get_premissions();       //here i get a fatal error

    private function get_premissions() {
        $query_premissions = OpenCon()->prepare("SELECT * FROM uprawnienia WHERE id_pracownicy = :id");
        $query_premissions -> bindValue(':id', $current_id, PDO::PARAM_INT);
        $query_premissions -> execute();
        return $query_premissions -> fetch();
    }

    public function dostep_ustawienia() {
        if($uprawnienia['dostep_ustawienia']) return true;
        return false;
    }
}

I tried to change return to echo but i didn't helped. How can i achieve that? Thanks for any help.

VicotrLeet
  • 23
  • 3
  • You can't directly assign function results in classes. That's what constructors are for. – El_Vanja Mar 28 '20 at 23:38
  • By the way, this is where your next error will be: `if($uprawnienia['dostep_ustawienia'])`. Please read more about using classes and their properties. – El_Vanja Mar 28 '20 at 23:40
  • Read more details here: [PHP Error : Fatal error: Constant expression contains invalid operations](https://stackoverflow.com/questions/40171546/php-error-fatal-error-constant-expression-contains-invalid-operations) – El_Vanja Mar 28 '20 at 23:41
  • So i have to fetch data from db in constructor? Is is the correct way of doing so? – VicotrLeet Mar 29 '20 at 09:40

1 Answers1

1

You need to assign data directly to private variable

$this->uprawnienia  = $query_premissions->fetch();

And then use this private variable:

if($this->uprawnienia['dostep_ustawienia']) return true;
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98