2

For some reason this is giving me the follow error: syntax error, unexpected T_VARIABLE:

 $mysql = json_decode(getenv("VCAP_SERVICES"));
 $mysql = $mysql["mysql-5.1"][0]["credentials"];

class DATABASE_CONFIG {

    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'port' => $mysql['port'],  // <-- Line with error
        'login' => $mysql['username'],
        'password' => $mysql['password'],
        'database' => $mysql['name'],
        'prefix' => ''
        //'encoding' => 'utf8',
    );

    public $test = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'user',
        'password' => 'password',
        'database' => 'test_database_name',
        'prefix' => '',
        //'encoding' => 'utf8',
    );
}

I know you can use variables as values in arrays, so what is going on?

1
  • even though it isn't a variable of the class? i understand i couldn't use $test in $default, but i thought if the variable existed outside the class that it would work Commented Jan 3, 2013 at 9:03

3 Answers 3

3

It looks like you're trying to set the default value of a property to a variable.

You can't do that, not even inside an array. This is half PHP's parser sucking, a quarter of PHP's lack of appropriate error message, and a bit of sanity.

You'll need to do it from within the constructor instead by passing in $mysql:

$config = new DATABASE_CONFIG($mysql);

class DATABASE_CONFIG {

    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'port' => null,
        'login' => null,
        'password' => null,
        'database' => null,
        'prefix' => ''
        //'encoding' => 'utf8',
    );

    public function __construct($mysql) {
        $this->default['port'] = $mysql['port']; // etc
    }

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

Comments

0

$mysql has no scope inside the class. You need to inject it as an argument into the class constructor, and then define your array values for the class properties

Comments

0

You're trying to reference a variable inside a class which is defined outside of that class.

PHP has no idea what $mysql is inside of that class definition.

Comments

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.