-1

我正在尝试 OOP PHP,我似乎遇到了一些问题。

    class Connection
{   
    public $con = false;
    public $dbSelected = false;
    public $activeConnection = null;
    public $dataBaseName = "";
    function __contruct($dbUserName, $dbPassword, $server = "localhost")
    {
        $this->con = mysql_connect($server,$dbUserName,$dbPassword);
        if(!$this->con)
        {
            $this->activeConnection = false;
        }
        else
        {
            $this->activeConnection = true;
        }
    }
    // Says the error is on the line bellow
    public function dbConnect($dbName, $identifyer = $this->con)
    {
        $this->dbSelected = mysql_select_db($dbName, $identifyer);
        $this->dataBaseName = $dbName;
        if($this->dbSelected != true)
        {
            $this->connectionErrorReport();
        }
    }
    //... Class continues on but is unimportant. 

我收到 Parse 错误:第 21 行的 [path] 中出现意外的 T_VARIABLE 语法错误

我已经盯着它看了这么久,我真的需要一些帮助。

4

8 回答 8

4

问题在这里:

public function dbConnect($dbName, $identifyer = $this->con) { ... }

应该是这样的:

public function dbConnect($dbName, $identifyer = null)
{
    $identifyer = $identifyer ? $identifyer : $this->con;
    ...
}
于 2012-03-13T20:38:22.377 回答
4

这不是一个有效的语法。做这个:

public function dbConnect($dbName, $identifyer = null)
{
    if ($identifyer === null)
      $identifyer = this->con;
    //...
}
于 2012-03-13T20:39:01.720 回答
3
public function dbConnect($dbName, $identifyer = $this->con)

您不能将变量用作默认参数。您需要设置$identifyer一个值。

你可以这样做:

public function dbConnect($dbName, $identifyer = FALSE){
    $identifyer = $identifyer === FALSE ? $this->con : $identifyer;
    // rest of function
}
于 2012-03-13T20:38:00.520 回答
3

当您为函数参数分配默认值时,它必须是常量,不能是运行时分配的值。

例如:

public function dbConnect($dbName, $identifyer = 12345) //this is okay

public function dbConnect($dbName, $identifyer = $something) //this is not okay
于 2012-03-13T20:38:24.853 回答
1

你不能这样说: $identifyer = $this->con

尝试将默认值设置为 NULL 并在方法中检查它。

于 2012-03-13T20:38:47.647 回答
0

$this->con 是个问题,但作为一个公共函数,你可以访问 $this->con。

 public function dbConnect($dbName )
 {
    $identifyer = $this->con;
    $this->dbSelected = mysql_select_db($dbName, $identifyer);
    $this->dataBaseName = $dbName;
    if($this->dbSelected != true)
    {
        $this->connectionErrorReport();
    }
 }
于 2012-03-13T20:39:34.390 回答
0

问题是因为

$identifyer = $this->con)

php 文档指出,对于默认参数值...The default value must be a constant expression, not (for example) a variable, a class member or a function call.

于 2012-03-13T21:01:01.363 回答
-1

public $identifyer = $this->con简单地替换为$identifyer.

您只能将静态变量作为参数的默认值传递,如下所示public function test($value = self::default_value)

这应该有效:

public function dbConnect($dbName, $identifyer = NULL)
{
    NULL === $identifyer AND $identifyer = $this->con;
    $this->dbSelected = mysql_select_db($dbName, $identifyer);
    $this->dataBaseName = $dbName;
    if($this->dbSelected != true)
    {
        $this->connectionErrorReport();
    }
}
于 2012-03-13T20:41:35.447 回答