Unexpected error T_VARIABLE

Well, I know this is a fairly common question, but all the solutions that I have found so far are related to the missing half-time or curly brace, both of which I know, are not for me.

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

session.php:

<?php class session { ... var $host = 'localhost'; ... } ?> 

Great. But I want my database data to be in a different 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']; ... } ?> 

What then gave me this error: Parse error: syntax error, unexpected T_VARIABLE in ../session.php on line 74 , where line 74 is my destination var $host .

I even tried to do this in session.php , just to make sure the problem is not include:

session.php

 <?php # include('db_creds.php'); class session { ... var $db_host = 'localhost'; var $host = $db_host; ... } ?> 

... but this only causes the same error as above.

Can someone tell me what is going on here? I am on my way!

+7
variables include php
source share
2 answers

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

[...] this initialization must be a constant value

[ Source: php.net manual ]

Use the constructor to correctly initialize the value:

 class session { var $host; function __construct() { $this->host = $db_creds['host']; } } 
+9
source share
  • the first letter in the class name must be capital (class Session)

  • You are writing a constructor

  • Class properties are accessed using $ this-> property

-one
source share

All Articles