Skip to content
Advertisement

How to call a local property using OOP?

I’m a beginner looking to learn more about PHP OOP, so there are things I don’t know, in the ShowUsers() method, I would like to display all users in the database, but I’m not getting it, because I don’t know how to call the connection property.

If I’ve been using encapsulation, it would be easy, but I’m using the connection property as local, and I really don’t know how to call this property, how can I call it without using encapsulation?

db.php

<?php


class DbConnect {
    private $host = 'localhost';
    private $dbname = 'database';
    private $username = 'root';
    private $password = '';

    public function __construct() {
        try {
            $conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $exception) {
            throw new Exception($exception->getMessage());
        }
    }
} 

main.php

<?php

require_once 'db.php';

class Main extends DbConnect {

    public function __construct() {
        parent::__construct();
    }

    public function ShowUsers() {
        $sql = "SELECT * FROM users";
        $result = parent::__construct()->prepare($sql); //Problem here
        $result->execute();
    }
}

$object = new Main();
$object->ShowUsers();

Note: I don’t want to use encapsulation to make it work, I want to learn how to call the variable without using encapsulation, if possible.

Advertisement

Answer

Based on the code above and the comments, I recommend that you declare $conn as protected in your DbConnect class:

<?php
// db.php  

class DbConnect {
    private $host = 'localhost';
    private $dbname = 'database';
    private $username = 'root';
    private $password = '';
    protected $conn;
    public function __construct() {
        try {
            $this->conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $exception) {
            throw new Exception($exception->getMessage());
        }
    }
} 

Then in main.php, you can do:

<?php
// main.php

require_once 'db.php';

class Main extends DbConnect {

    public function __construct() {
        parent::__construct();
    }

    public function ShowUsers() {
        $sql = "SELECT * FROM users";
        $result = $this->conn->prepare($sql);
        $result->execute();
    }
}

$object = new Main();
$object->ShowUsers();
?>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement