Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse error when concat'ing a defined variable and string in a class [closed]

I have defined a variable in a separate config file:

define('URL', 'someurl.co.uk');

However, when I try to use it to concat with a string inside a class:

class AdminEmail extends Email {

   private $from = "jsmith".URL;

I get the following error:

Parse error: parse error, expecting `','' or `';'' 

But if I echo it out, it displays perfectly!

Hope I haven't missed anything obvious here!

like image 849
davidandrew Avatar asked Jul 20 '10 09:07

davidandrew


People also ask

How do you concatenate strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do you concatenate variables in JavaScript?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.


2 Answers

You can't use constants, functions or other variables when pre-defining class variables. Class definitions are like blueprints, they must be completely independent from anything else going on in the script (except for dependencies on other classes of course.)

You would have to set this later, e.g. in the constructor:

class AdminEmail extends Email {

   private $from;

   function __construct()
   {
     $this->from = "jsmith".URL;
   }

or in a separate function:

   function setFrom($from)
    {
     $this->from = $from;
    }
like image 186
Pekka Avatar answered Sep 21 '22 13:09

Pekka


You can use constants, but not functions or other variables when pre-defining class variables. Also you cannot use operators like the . dot string concatenation operator.

See the PHP OO Manual for the details. Do take note that you can use the array() construct when pre-defining class variables. array() is not a function but a language construct.

In this case you have indeed two paths to choose from as a solution. You can define the value in the constructor:

class AdminEmail extends Email {

  private $from;

  function __construct()
  {
     $this->from = "jsmith".URL;
  }

The other solution is to always retrieve the value using a function:

class AdminEmail extends Email {

  private $from;

  function getFrom()
  {
     if (null === $this->from) {
         $this->from = "jsmith" . URL;
     }
     return $this->from;
  }
like image 40
Matijs Avatar answered Sep 21 '22 13:09

Matijs