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!
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.
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.
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With