jak1502
jak1502

Reputation: 13

PHP Variable in a Class array

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.

Upvotes: 1

Views: 80

Answers (3)

Madara's Ghost
Madara's Ghost

Reputation: 175088

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.

Upvotes: 4

Ashwin Parmar
Ashwin Parmar

Reputation: 3045

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

}

Upvotes: 1

roycable
roycable

Reputation: 301

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

Upvotes: -1

Related Questions