2

I am trying to reference a public variable from inside a class.

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

But this gives back a parse error:

Parse error: parse error

What is the correct way of doing this?

Eli Stone
  • 1,515
  • 4
  • 33
  • 57
  • 1
    `"$this->CompanyName - big website"` should be `$this->CompanyName ." - big website"` – Dave Apr 30 '13 at 12:41
  • 5
    @Dave - No it shouldn't, that'll still produce a parse error, because you can't initialize member variables to anything that is non-static. – nickb Apr 30 '13 at 12:42
  • Yeah I just fixed the obvious error didn't even look at the rest tbh – Dave Apr 30 '13 at 12:44

3 Answers3

3

you can't use $this on the properties, but in the methods, try to define the pagetitle in the __construct();

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

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

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

outputs: MyWebsite - big Website

aleation
  • 4,796
  • 1
  • 21
  • 35
2

You can't set variable with other variable when defining. Use __construct for it:

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

    public function __construct(){
        $this->PageTitle = $this->CompanyName." - big website";
    }
}
Narek
  • 3,813
  • 4
  • 42
  • 58
2

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

This declaration may include an initialization, but this initialization must be a constant value

it's not valid.

this is not valid:

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

but this is:

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

I'll do it this way :

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

    public function __construct(){
       $this->$CompanyName = 'mywebsite';
       $this->PageTitle = $this->CompanyName." - big website";
   }
}
egig
  • 4,370
  • 5
  • 29
  • 50