意外的T_VARIABLE错误 [英] Unexpected T_VARIABLE error

查看:149
本文介绍了意外的T_VARIABLE错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我知道这是一个很常见的问题,但到目前为止我发现的所有解决方案都涉及缺少分号或大括号,我知道这两种情况都不适合我。

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.

我有一个使用此变量赋值的FINE类:

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'];
     ...
   }

?>

然后给了我这个错误:解析错误:语法错误,意外T_VARIABLE在第74行的../session.php 中,其中第74行是我的 var $ host 赋值。

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

我甚至尝试在 session.php 中这样做,只是为了确保问题不在包含中:

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!

推荐答案

此处不允许变量,属性必须由PHP中的常量初始化:

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


[...]此初始化必须是常量值

[…] this initialization must be a constant value

[资料来源:php.net手册]

使用构造函数正确初始化值:

Use the constructor to intialize the value properly:

class session {
    var $host;

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

这篇关于意外的T_VARIABLE错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆