开发者

Unexpected T_VARIABLE error

开发者 https://www.devze.com 2022-12-11 07:18 出处:网络
Okay, I know this is a common enough question, but all the solutions I\'ve found thus far have involved a missing semi-colon or curly brace, both of which I know is not the case for me.

Okay, I know this is a common enough question, but all the solutions I've found thus far have involved a missing semi-colon or curly brace, both of which I know is not the case for me.

I have a class that works FINE with this variable assignment:

session.php:

<?php

   class session {
     ... 
     var $host = 'localhost';
     ...
   }

?>

Great. But I want to have my database details in another file, so I did this:

db_creds.php:

<?php

   var $db_creds = array(
      'host' => 'localhost',
      ...
   );

?>

session.php

<?php

   include('db_creds.php');

   class session {
     ... 
     var $host = $db_creds['host'];
     ...
   }

?>

Which then gave me this error:开发者_如何学Python Parse error: syntax error, unexpected T_VARIABLE in ../session.php on line 74, where line 74 is my var $host assignment.

I even tried doing this in session.php, just to be sure the problem wasn't in the include:

session.php

<?php

   # include('db_creds.php');

   class session {
     ...
     var $db_host = 'localhost';
     var $host = $db_host;
     ...
   }

?>

... but that just throws the same error as above.

Can anyone tell me what's happening here? I'm at my wits end!


Variables are not allowed here, properties must be initialized by constants in PHP:

[…] this initialization must be a constant value

[Source: php.net manual]

Use the constructor to intialize the value properly:

class session {
    var $host;

    function __construct() {
        $this->host = $db_creds['host'];
    }
}


  1. the first letter in a class name should be capital (class Session)

  2. did you write a constructor

  3. class properties are accessed with $this->property

0

精彩评论

暂无评论...
验证码 换一张
取 消