phpclassoopconditional-operator

Ternary operator syntax error in class declaration


I want to use ternary operator to assign two different values to the class variable.

I have following code sample where i am getting fatal error.

    class test {
         public $data = (true) ? "working" : "not working"; //Parse error: syntax error, unexpected '(' in C:\xampp\htdocs\Faltu\test.php on line 15

         function __construct() {
            echo $this->data;
         }  
    }
    $test = new test(); 

I have tried without class and it's working fine but in class I'm getting error.

Can anyone guide me how to achieve this?


Solution

  • You may only assign constant values when declaring properties, you cannot perform logical operations, like a ternary.

    You can perform your logic in your __construct function:

    class test {
         public $data = NULL;
    
         function __construct() {
            $this -> data = true ? "working" : "not working";
            echo $this -> data; // working
         }  
    }
    $test = new test();
    

    From the documentation:

    This 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.