OOP PHP unexpected T_VARIABLE



我正在尝试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. 

我得到一个分析错误:语法错误,在第21行的[path]中出现意外的T_VARIABLE

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

这不是一个有效的语法。这样做:
public function dbConnect($dbName, $identifyer = null)
{
    if ($identifyer === null)
      $identifyer = this->con;
    //...
}

问题就在这里:

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

应该是这样的:

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

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

你可以这样做:

public function dbConnect($dbName, $identifyer = FALSE){
    $identifyer = $identifyer === FALSE ? $this->con : $identifyer;
    // rest of function
}

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

例如:

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

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

尝试将默认值设置为NULL,然后在方法中进行检查。

$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();
    }
 }

问题是由于

$identifyer = $this->con)

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

用简单的$identifyer替换public $identifyer = $this->con

只能将静态变量作为参数的默认值传递,如下所示: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();
    }
}

相关内容

  • 没有找到相关文章

最新更新