【问题标题】:PHP Reference variable in a class [duplicate]类中的PHP引用变量[重复]
【发布时间】:2013-04-24 09:22:01
【问题描述】:

我正在尝试从一个类中引用一个公共变量。

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

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

Parse error: parse error

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

【问题讨论】:

  • "$this->CompanyName - big website" 应该是$this->CompanyName ." - big website"
  • @Dave - 不应该,这仍然会产生解析错误,因为您无法将成员变量初始化为非静态的任何内容。
  • 是的,我刚刚修复了明显的错误,甚至没有查看其余部分

标签: php


【解决方案1】:

你不能在属性上使用$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 - 大网站

【讨论】:

    【解决方案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";
        }
    }
    

    【讨论】:

      【解决方案3】:

      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";
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多