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?