views:

22

answers:

2

Hi guys,

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!

Many thanks

+4  A: 

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;
    }
Pekka
Thanks a lot, I've just started to learn OOP so I bet this is pretty basic stuff. Cheers again!
daveyWavey
Don't worry, davey. Trying to concat. a string to use as a class property caught me out when I was starting out too!
Martin Bean
A: 

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