【问题标题】:Mysql - Parse error (syntax error) in my code [duplicate]Mysql - 我的代码中的解析错误(语法错误)[重复]
【发布时间】:2014-09-09 15:11:07
【问题描述】:

当我使用时:

$mysqli = new mysqli('localhost', 'root', '', 'cms');

在我的课堂上,结果显示错误:

Parse error: syntax error, unexpected '$mysqli' (T_VARIABLE), expecting function (T_FUNCTION) in D:\xamppp\htdocs\cms\includes\td-class-db.php on line 12

并且当使用$mysqli = new mysqli('localhost', 'root', '', 'cms'); 超出类时不会显示任何错误!

我的班级:

class Connect_db{
  $mysqli = new mysqli('localhost', 'root', '', 'cms');
}

为什么?

【问题讨论】:

  • 把它放在__construct()。应该是$this->mysqli = etc...

标签: php mysql mysqli


【解决方案1】:

在类中创建成员变量时不能实例化类。您必须在构造函数或方法中执行此操作:

class Connect_db{
    private $mysqli;

    public function __constructor() {
        $this->mysqli = new mysqli('localhost', 'root', '', 'cms');
    }
}

【讨论】:

  • thanx John Conde 如何为这个函数使用静态函数?
  • 为什么这需要是静态的?
  • 我所有的函数都是静态的并且易于使用。错了吗?
  • 方法只需要在某些情况下是静态的。这不是很常见。这不是其中一种情况。
【解决方案2】:

将您的代码放入类方法中,例如构造函数。

class Connect_db
{

  function __construct()
  {
    $mysqli = new mysqli('localhost', 'root', '', 'cms');
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2018-06-28
    • 2016-02-07
    • 1970-01-01
    相关资源
    最近更新 更多