Reputation: 2231
I have class with constant variable but I get this error
syntax error, unexpected '$_SERVER' (T_VARIABLE)
Here is my code
<?php
namespace common\models;
class EConstant
{
....
const HomeUrl = 'http://'.$_SERVER['SERVER_NAME'].'/someweb/';
....
}
What wrong with my code?
Upvotes: 1
Views: 2855
Reputation: 18021
Saravanan Sampathkumar's answer is proper but not complete.
As Guide states:
When extending your class from
yii\base\Component
oryii\base\Object
, it is recommended that you follow these conventions:
- If you override the constructor, specify a$config
parameter as the constructor's last parameter, and then pass this parameter to the parent constructor.
- Always call the parent constructor at the end of your overriding constructor.
- If you override theyii\base\Object::init()
method, make sure you call the parent implementation ofinit()
at the beginning of yourinit()
method.
So it should be:
public function __construct($config)
{
$this->homeURL = 'http://' . $_SERVER['SERVER_NAME'] . '/someweb/';
parent::__construct($config);
}
or init()
should be used instead like:
public function init()
{
parent::init();
$this->homeURL = 'http://' . $_SERVER['SERVER_NAME'] . '/someweb/';
}
It might be worth to mention that you should not fully trust this $_SERVER['SERVER_NAME']
variable as it can be tampered. At least check if the incoming value is on the expected values list if possible.
Upvotes: 1
Reputation: 3261
You can not do that, instead try this,
<?php
class EConstant
{
protected $homeURL;
public function __construct() {
$this->homeURL = 'http://'.$_SERVER['SERVER_NAME'].'/someweb/';
}
}
Upvotes: 2