我试图从类中引用一个公共变量。
class Settings{
public $CompanyName = "MyWebsite"; // company name
public $PageTitle = "$this->CompanyName - big website"; // E.g. My Big Website
}
但是这会给出一个解析错误:
Parse error: parse error
这样做的正确方法是什么?
答案 0 :(得分:3)
你不能在属性上使用$ this,但在方法中,尝试在__construct()
中定义pagetitle;
class Settings{
public $CompanyName = "MyWebsite"; // company name
public $PageTitle;
function __construct(){
$this->PageTitle = "$this->CompanyName - big Website";
}
}
$settings = new Settings();
echo $settings->PageTitle;
输出:MyWebsite - 大网站
答案 1 :(得分: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";
}
}
答案 2 :(得分:1)
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";
}
}