php pdo mysql connect - 令人困惑的语法问题

时间:2011-03-23 20:07:58

标签: php

<?php
$mysql_host='mysql1.000webhost.com';
$mysql_dbname='a8130617_skola';
$mysql_username='something';
$mysql_password='something';

class mysql {
    try{
    public $db = new PDO("mysql:host=$mysql_host;dbname=$mysql_dbname",
            $mysql_username, $mysql_password);
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }
} //ERROR EXCLAMATION MARK HERE???
?>

为什么netbeans 6.9.1认为这是假语法? 非常感谢

2 个答案:

答案 0 :(得分:4)

你对OOP有什么了解吗?

类应包含字段和/或方法。您刚刚用class{}包围了一段代码。这不是编程。

阅读PHP中的OOP - 这是手册:http://php.net/manual/en/language.oop5.php

为了你自己的利益而阅读它。

编辑:

我知道下面的例子会让你很懒,但我会拍摄并相信你会读更多。

连接的示例类可以如下所示:

class Mysql {

    protected $_host;
    protected $_dbname;
    protected $_username;
    protected $_password;
    protected $_db;

    public function __construct($host = null, $dbname = null, $username = null, $password = null)
    {
        $this->_host = $host;
        $this->_dbname = $dbname;
        $this->_username = $username;
        $this->_password = $password;
    }

    public function connect()
    {
        try {
            $this->_db = new PDO('mysql:host=' . $this->_host . ';dbname=' . $this->_dbname, $this->_username, $this->_password);
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
    }

    public function getDb()
    {
        return $this->db;
    }

    public function setHost($host)
    {
        $this->_host = $host;
        return $this;
    }

    public function getHost()
    {
        return $this->_host;
    }

    public function setDbname($dbname)
    {
        $this->_dbname = $dbname;
        return $this;
    }

    public function getDbname()
    {
        return $this->_dbname;
    }

    public function setUsername($username)
    {
        $this->_username = $username;
        return $this;
    }

    public function getUsername()
    {
        return $this->_username;
    }

    public function setPassword($password)
    {
        $this->_password = $password;
        return $this;
    }

    public function getPassword()
    {
        return $this->_password;
    }


}

示例用法:

$mysql = new Mysql('mysql1.000webhost.com', 'a8130617_skola', 'something', 'something');
$mysql->connect();

答案 1 :(得分:0)

try{
public $db = new PDO("mysql:host=$mysql_host;dbname=$mysql_dbname",
        $mysql_username, $mysql_password);
}
catch(PDOException $e){
    echo $e->getMessage();
}

尝试catch块需要在方法内部。但是要坚持下去,不确定为什么要把它包装在课堂上?您的类是已定义类的包装器。