2
var $foo = array('foo' => $bar);

I am getting an UNEXPECTED T_VARIABLE error. I can't use variables when creating arrays?

This declaration is inside a class, and I am running PHP v5.3.2

When removing the var, I get another error Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION

Thanks

AlexBrand
  • 11,971
  • 20
  • 87
  • 132

3 Answers3

6

var is not PHP syntax... A simple

$foo = array('foo' => $bar);

would suffice.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • @alex: You cannot declare 'dynamic' variables in a class. They have to evaluate out to constants. `$var = array('a' => 'b')` would b efine, because that's all constant. You've got `$bar` in there, which is not constant, hence the error. If you need to dynamically assign a variable in the object like that, you have to do it in the constructor. – Marc B Aug 03 '11 at 19:51
  • Yes. A member variable HAS to be completely constant. no variable portions allowed. – Marc B Aug 03 '11 at 19:54
1

The keyword var is only used when declaring variables (i.e. instance variables) in classes, but even that is PHP4 syntax and is currently deprecated. This will do what you want:

$foo = array('foo' => $bar);
Jeremy Roman
  • 16,137
  • 1
  • 43
  • 44
  • There is no 'var' keyword in PHP, period. There's global/protected/private/public prefixes for variables, but no 'var'. – Marc B Aug 03 '11 at 19:43
  • 1
    If you're on a sufficiently recent version of PHP, I think it's actually completely deprecated. As of PHP 5.4 (if I recall correctly), just don't use `var`. – Jeremy Roman Aug 03 '11 at 19:43
  • 2
    http://www.php.net/manual/en/language.oop5.properties.php - `In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning.`... Just to keep in mind – Timur Aug 03 '11 at 19:43
  • Marc B: It was a keyword in previous versions of PHP, which is why the lexer is picking up T_VARIABLE at all. – Jeremy Roman Aug 03 '11 at 19:44
0

try:

$foo = array('foo' => $bar);

See this question for why you are having trouble: What does PHP keyword 'var' do?

Community
  • 1
  • 1
Schleis
  • 41,516
  • 7
  • 68
  • 87