6

here is the fatal error:

Fatal error: Constant expression contains invalid operations

I get a fatal error in this code:

<?php

class InfoClass {

    private $user_agent = $_SERVER['HTTP_USER_AGENT']; // error is on this line

    public static function getOS() { 

        global $user_agent;

        $os_platform = "Unknown OS Platform";

        ...
}

i am using php 7. why is this error showing? thanks

pixie123
  • 929
  • 3
  • 14
  • 27
  • 2
    Because `$_SERVER['HTTP_USER_AGENT'];` is "run-time" information; and class property `declaration may include an initialization, but this initialization must be a constant value -- that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.` – Mark Baker Jan 02 '17 at 00:13
  • @MarkBaker ok how do i fix it then? – pixie123 Jan 02 '17 at 00:14
  • You assign it in the class constructor, and instatiate an object... and wtf is `global $user_agent;` supposed to be? Is it something that should be passed as an argument to the method? – Mark Baker Jan 02 '17 at 00:15
  • @MarkBaker i dont know, i got this from this post: http://stackoverflow.com/a/18070424/4357238 – pixie123 Jan 02 '17 at 00:17
  • The problem is that constant does not have a value when that line is executed by PHP. To resolve it, you can initialise the variable as an empty string, and then assign it a value inside the method. However, this code is bad design. Perhaps you should try to restructure the flow. – Amal Murali Jan 02 '17 at 00:28
  • @AmalMurali pls suggest the restructure of the flow – pixie123 Jan 02 '17 at 00:29

1 Answers1

7

Do This Instead

<?php

class InfoClass {
    private $user_agent;
    public function __construct(){
        $this->user_agent = $_SERVER['HTTP_USER_AGENT']; // error is on this line
    }

    public static function getOS() { 

    global $user_agent;

    $os_platform = "Unknown OS Platform";

    ...
}

Hope it Helps

funsholaniyi
  • 435
  • 2
  • 12