我试图从类内部引用一个公共变量。
class Settings{
public $CompanyName = "MyWebsite"; // company name
public $PageTitle = "$this->CompanyName - big website"; // E.g. My Big Website
}
但是这会返回一个解析错误:
Parse error: parse error
正确的做法是什么?
您不能在属性上使用$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 - big Website
定义时不能将变量设置为其他变量。对它使用__construct:
class Settings{
public $CompanyName = "MyWebsite"; // company name
public $PageTitle; // E.g. My Big Website
public function __construct(){
$this->PageTitle = $this->CompanyName." - big website";
}
}
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";
}
}