Nathan
Nathan

Reputation: 5372

Set a variable to what json_encode() outputs in PHP

json_encode() returns a string...

So shouldn't the following code work?

class TestClass {
    private $test = json_encode("test");
}

PHP outputs

Parse error: syntax error, unexpected '(', expecting ',' or ';' in /home/testuser/public_html/test.php on line 10

Upvotes: 1

Views: 846

Answers (2)

Shakti Singh
Shakti Singh

Reputation: 86376

You can not assign expression or any variable while declaring class property. The literal constants such as __FILE__ are allowed here.

they have to be a literal value, such as a string, or a constant.

There all work.

private $test= 98;
private $test= "test value";
private $test= CONSTANT;
private $test= __FILE__;

But these will not

private $test= 98*2;
private $test= "test value"."some other value";

You can use constructor

 function __construct() {
        $this->test = json_encode("test");
    }

Upvotes: 4

Brenton Alker
Brenton Alker

Reputation: 9072

In PHP you cannot assign an instance variable to the result of a function in the declaration. You should assign it in the constructor. Eg.

class TestClass {
    private $test;
    public function __construct() {
        $this->test = json_encode("test");
    }
}

Upvotes: 2

Related Questions