2

我正在尝试从类内部引用公共变量。

class Settings{
    public $CompanyName = "MyWebsite"; // company name
    public $PageTitle   = "$this->CompanyName - big website"; // E.g. My Big Website
}

但这会返回一个解析错误:

Parse error: parse error

这样做的正确方法是什么?

4

3 回答 3

3

您不能在属性上使用 $this,但在方法中,尝试在__construct();中定义页面标题

class Settings{
    public $CompanyName = "MyWebsite"; // company name
    public $PageTitle;

    function __construct(){
        $this->PageTitle = "$this->CompanyName - big Website";
    }
}

$settings = new Settings();
echo $settings->PageTitle;

输出:MyWebsite - 大网站

于 2013-04-30T12:46:32.193 回答
2

定义时不能用其他变量设置变量。使用__construct

class Settings{
    public $CompanyName = "MyWebsite"; // company name
    public $PageTitle; // E.g. My Big Website

    public function __construct(){
        $this->PageTitle = $this->CompanyName." - big website";
    }
}
于 2013-04-30T12:45:14.063 回答
2

http://php.net/manual/en/language.oop5.properties.php

这个声明可以包含一个初始化,但是这个初始化必须是一个常量值

这是无效的。

这是无效的:

public $var1 = 'hello ' . 'world';

但这是:

public $var1 = myConstant;
public $params = array();

我会这样做:

class Settings{
    public $CompanyName;
    public $PageTitle; // E.g. My Big Website

    public function __construct(){
       $this->$CompanyName = 'mywebsite';
       $this->PageTitle = $this->CompanyName." - big website";
   }
}
于 2013-04-30T12:48:04.623 回答