Home » Php » php – Parse error when concat'ing a defined variable and string in a class

php – Parse error when concat'ing a defined variable and string in a class

Posted by: admin July 12, 2020 Leave a comment

Questions:

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!

How to&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;
    }

Answer:

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