Call class function: MinPDO :: connect ();

1

I have a class called MinPDO and inside it a function called connect :

class MinPDO {

    public $sgbd = "mysql";
    public $dbhost = "localhost";
    public $dbname = "minpdo";
    public $dbuser = "root";
    public $dbpass = "";

    public function connect() {
        try {
            $conn = new PDO("{$this->sgbd}:host={$this->dbhost};dbname={$this->dbname};charset=utf8;", $this->dbuser, $this->dbpass);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            return $conn;
        } catch (PDOException $ex) {
            echo "<br><b>Error:</b> " . $ex->getMessage();
            return false;
        }
    }
}

How can I call it that?

MinPDO::connect();

I'm currently doing this:

$mnpdo = new MinPDO();
$mnpdo->connect();

According to some programmers it would be more useful to call it the first form, but how do I do it?

    
asked by anonymous 26.12.2015 / 18:45

1 answer

3

:: , indicates the call of a method or static or constant property. Just add the keyword static .

public static function connect()

To properly mount the PDO constructor, you can transform instance variables into static members as well, or it means that these properties will be available through the class rather than a specific object.

$conn = new PDO(self::$sgbd.":host=".self::$dbhost.";dbname=".self::$dbname.";charset=utf8;", self::$dbuser, self::$dbpass);

Related:

When to use self vs $ this in PHP?

What is the name of the :: operator in PHP?

    
26.12.2015 / 18:48