Problem with Parse error: syntax error, unexpected T_VARIABLE

1

I'm having trouble inserting a variable into an array ... I did a search here and did not find any similar question that could help me solve this, so I'm creating this one.

The error: Parse error: syntax error, unexpected T_VARIABLE points to line 26

On line 26 I have this:

var $users = array('user1' => $senha);

The variable $ password that is causing the error ... if I put a string any functions without error.

    
asked by anonymous 22.07.2015 / 14:37

1 answer

8

The Parse error: syntax error, unexpected T_VARIABLE means that PHP was not expecting a variable at any given time.

This error can occur in some situations, but your question includes some special cases.

The most common problem is the absence of a comma point in the previous line. The interpreter in this case informed the error in the next line that occurs, and not in the line where the semicolon is missing:

<?php

$var = 1
$var2 = 3;

Returns the error:

  

Parse error: syntax error, unexpected '$ var2' (T_VARIABLE) in path / file on line 4

Another problem is in the definition of the word var before the variable in a context outside of a class.

This keyword was used in PHP 4 to define class properties, and currently exists only to maintain comparability with old codes.

In recent versions, it is a synonym for public .

Simply remove var when defining variables in PHP.

$users = array('user1' => $senha);

Now, if you are setting $user to a class property, the problem is that it is not possible to define dynamic values directly in the class definition (basically variables or functions), such as be noted in the documentation .

<?php
class SimpleClass
{
   // declaração de propriedades invalidas:
   // ...
   public $var5 = $myVar;

}

This explains why var $users = array('user1' => 'Blabla'); works.

Recommendations

  • See if the line above the one entered in the error ends with ;

  • Do not use var in PHP 5 onwards, prefer private , protected or public .

  • If you need to define dynamic values in the class property, you can do this by the constructor method:

    <?php
    class SimpleClass
    {
    
       public $users = array();
    
       public function __construct($senha){
           $this->users = array('user1' => $senha);
    
           // ...
       }
    
    }
    
  • 22.07.2015 / 14:54