【问题标题】:Set a variable to what json_encode() outputs in PHP将变量设置为 json_encode() 在 PHP 中的输出
【发布时间】:2011-04-12 06:33:55
【问题描述】:

json_encode() 返回一个字符串...

那么下面的代码不应该工作吗?

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

PHP 输出

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

【问题讨论】:

    标签: php json


    【解决方案1】:

    在声明类属性时,您不能分配表达式或任何变量。此处允许使用诸如 __FILE__ 之类的文字常量。

    它们必须是文字值,例如字符串或常量。

    一切顺利。

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

    但这些不会

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

    你可以使用构造函数

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

    【讨论】:

      【解决方案2】:

      在 PHP 中,您不能在声明中将实例变量分配给函数的结果。您应该在构造函数中分配它。例如。

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

      【讨论】:

        猜你喜欢
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        • 2016-01-10
        • 2011-06-06
        相关资源
        最近更新 更多