如何访问私有财产/方法? [关闭]

I'm new to OOP programming and i'm trying to set up a private class db, for database connection:

My class:

class db
{
private $_db;

private function db()   
{
$this->db = new mysqli('localhost','x','x','x');
$this->db->set_charset('utf');
}
}

In another file I have the following code:

$db = new db();
                $sql = "SELECT news, DATE_FORMAT(date, '%D %b') AS date FROM news ORDER       
BY DATE_FORMAT(date, '%Y, %m, %d') DESC LIMIT 3";
                $r = $db->db->query($sql);
                while($row=$r->fetch_assoc())
                {
                    echo '<b>'. $row['date'] . '</b></br> ' . $row['news'] .'</br>   
</br>';
                }

It works grand for public but not for private.

I was reading that private methods can only be accessed within the class but can't really understand how to do it. Can anyone please give me a hint?

Regards Jack

I'm not sure why your method is private. Essentially, any methods you want to use external to the class should be public. This leads to the creation of getters and setters.

Getters return private variable fields and setters set those fields to new values. This is just a safe way to enforce types and cleanly accept class modification.

One of the key principles of OOP is separation of interface from implementation. Class can be represented as a black box, where public methods and properties are used by the outer world to interact with your box.

While the private methods and properties are internal and are used to implement the functionality.

There is no need to make function db() private, as connection to the database must be provided as a function to the outer world by your class.

Private methods and private properties only reachable inside the same class (scope). The usage of private properties and methods should be well considered, private methods or private properites avoids any kind of reachability or inheritability by the heirs of the defining class.

Protected methods and private properties only reachable inside the same class and it heirs. Protected methods and privates are recommend for class-internal logic and their properties.