Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I concat strings for class variable definition in PHP?

Tags:

php

Inside my classes, Why I am able to declare a variable and set its value at the same time like this

 public $CSS_reset = "someValue";

Yet a syntax error occurs when i try to append two variables or strings like this

 public $CSS_reset = "someValue" . "appendedValue";   

The syntax error is Parse error: syntax error, unexpected '.', expecting ',' or ';'

This is my code ... with no syntax errors

class MyClass {

    private $css = "Mysite/CSS/";
    private $js = "Mysite/JS/"; 

    public $CSS_reset;        //Declare $CSS_reset but set it's value in the constructor
    public $CSS_styles; 


    function __construct() 
    {
         $CSS_reset = "reset.css" . "reset2.css";
         $CSS_styles = "styles.css" . "styles2.css";

    }

}

This is my code with syntax errors...

class MyClass {

    private $css = "Mysite/CSS/";
    private $js = "Mysite/JS/"; 

    public $CSS_reset = "reset.css" . "reset2.css";
    public $CSS_styles = "styles.css" . "styles2.css";

}

Not that I don't want to use the Constructor but the 2nd option with a syntax error is less code.

like image 841
Scott Avatar asked Mar 02 '26 19:03

Scott


1 Answers

You try to uses the properties css as if they were static, but they are not.

function __construct() 
{
     $this->CSS_reset = $this->css . "reset.css";
     $this->CSS_styles = $this->css . "styles.css";

}
like image 141
Asenar Avatar answered Mar 05 '26 04:03

Asenar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!