【问题标题】:In php class variable one equal second variable? [duplicate]在 php 类变量中,一个等于第二个变量? [复制]
【发布时间】:2017-01-22 18:54:31
【问题描述】:

这是我的代码:

class Config {
static public $site = 'http://localhost/site/';
static public $style = $site . 'css/style.css';

// ...
}

这不适合我。我得到白屏。

class Config {
    static public $site = 'http://localhost/site/';
    static public $style = 'http://localhost/site/css/style.css';

    // ...
    }

这是工作。我得到设计和代码。工作得很好。我的问题是为什么?

【问题讨论】:

  • 你能回显$style并与我们分享吗?
  • PHP Docs - 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..... 任何非常量值的串联,就其本质而言,都是运行时评估
  • $site . 'css/style.css';`` be valid anyway; it would need to be self::$site 也不会。 'css/style.css';`

标签: php


【解决方案1】:

这是不可能的:

static public $style = $site . 'css/style.css';

表达式不能用于初始化类值。只允许使用常量值。这是您必须在构造函数中执行的操作,但由于它们是静态值,因此无法保证在您尝试访问这些静态值之前该对象已被初始化。

class foo {
     public $foo = 1; // ok
     public $bar = 1+1; // ok only in PHP 5.6+
     public $baz = $this . $that; // not valid in any version of PHP 

您可以使用表达式(在 php 5.6+ 中)的唯一时间是结果值是否可以在编译时计算。所以1+1 可以,因为可以在编译时处理。但是$this . $that只能在运行时确定,因此是非法的。

【讨论】:

  • 我明白了。谢谢你。也许这样更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 2016-02-29
  • 1970-01-01
  • 2018-11-23
  • 2014-01-15
  • 1970-01-01
相关资源
最近更新 更多