Dark Cyber
Dark Cyber

Reputation: 2231

syntax error, unexpected '$_SERVER' (T_VARIABLE)

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

Answers (2)

Bizley
Bizley

Reputation: 18021

Saravanan Sampathkumar's answer is proper but not complete.

As Guide states:

When extending your class from yii\base\Component or yii\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 the yii\base\Object::init() method, make sure you call the parent implementation of init() at the beginning of your init() 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

Saravanan Sampathkumar
Saravanan Sampathkumar

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

Related Questions