1

I am trying to call a variable to add to an array within a class, but I keenp getting unexpected T_VARIABLE error when I try.

class MB_API {
    $SName = 'Test';
    $PWD = 'test';
    $SiteID = '10';
    protected $client;
    protected $sourceCredentials = array(
        "SourceName"=>$SName, 
        "Password"=>$PWD, 
        "SiteIDs"=>array($SiteID)
    );
};

The variables can be set within the class or outside, it doesn't really matter. They will be set by a pull from a database.

1
  • Would you edit your question to include the entire error message please? Commented Mar 10, 2014 at 10:50

3 Answers 3

4

Default variable values need to be compile time literals (They need to be constant before the script runs, basically, a "literal string", a number 42 or an array of constant values array(1, 2, 3)), meaning, they can't have a dynamic value (such as another variable).

A better way would be to use a constructor:

protected $sourceCredentials = []; //PHP5.4 and above syntax, synonymous to array()

public function __construct(array $sourceCredentials) {
    $this->sourceCredentials = $sourceCredentials;
}

Note that this way, it's up to the caller (the code that instantiated the object) to pass in the array of credentials from the outside. There are different ways of doing so, but this is considered best practice.

Sign up to request clarification or add additional context in comments.

2 Comments

To expand in a non technical way it means that $sourceCredentials can only be set as an empty array. You will have to fill it from within a method of MB_API
@CarlMarkham: Expanded and added an example :)
1

You can assign your variable value in constructor.

For best practice you use like this:

class MB_API {

    private $Sname;
    private $PWD;
    private $SiteID;
    protected $client;
    protected $sourceCredentials;

    public function __construct() {

        // Set your default Values here

        $this->Sname = "Test";
        $this->PWD = 'test';
        $this->SiteID - '10';

        $this->sourceCredentials = array(
            "SourceName" => $this->SName,
            "Password" => $this->PWD,
            "SiteIDs" => array($this->SiteID)
        );
    }

}

Comments

-1

You have two different "$sname" - one is $SName and another is $Sname

2 Comments

PHP is case insensitive, that's not the problem.
Ahhh, so it is. Getting my languages confused!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.