Call class function: Minpdo::connect();

Asked

Viewed 60 times

1

I have a class called MinPDO and within 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 her that?

MinPDO::connect();

At the moment I’m doing so:

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

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

  • 2

    Declaring the variables and the method as static.

1 answer

3


::, indicates the call of a static or constant method or property. Simply add the key plavara static.

public static function connect()

To properly assemble the PDO constructor, you can transform the instance variables into static members as well or that means these properties will be available through the class and not an object in specific.

$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?

  • 1

    It is important to note that the flame of the attributes must be changed too, without the $this-> how he’s doing.

  • @Diegofelipe, I was going to say exactly that, I had already tried putting us static, then he complains exactly about it, as I should put the variables?

  • Truth hadn’t noticed that, I’ll edit.

  • It worked, I’ll take a look at the links.. I edited the answer because the self is not recognized when we use {} to indicate variables, by concatenation only.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.