0

I'm trying out classes and PHP:PDO. I've set up a simple class to try out some stuff but I'm getting an error "Undefined variable: conn" error.

class Cms {

    function __construct() {
        try {
            $conn = new PDO('mysql:host=localhost;dbname=blog', 'root', '');
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $error) {
            echo 'error: ' . $error->getMessage();
        }
    }

    public function read() {
        $query = $conn->query("SELECT * FROM posts");
    }
}

To my knowledge this is probably because the $conn PDO object is not being passed onto the read method because it's being set in the construct method. What is the best(proper) way to let the read method be able to use the $conn attribute?

1 Answer 1

5
class Cms {

    private $_conn;

    function __construct() {
        try {
            $this->_conn = new PDO('mysql:host=localhost;dbname=blog', 'root', '');
            $this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $error) {
            echo 'error: ' . $error->getMessage();
        }
    }

    public function read() {
        $query = $this->_conn->query("SELECT * FROM posts");
    }
}

So you create a private property, assign your PDO instance to it and use

Some documentation: http://www.php.net/manual/en/language.oop5.properties.php

Sign up to request clarification or add additional context in comments.

2 Comments

That works, couple questions though. 1. Is this considered best practice? 2. Why use private? I'm not that familiar with visiblity yet, is this a case of "When i'm not using the $conn property outside the class might aswell make it private?".
@Stephan de Vries: 1. yep 2. because you don't want your class data to be changed without your permission

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.