0

I have a dbHandeller.php file . as follow

class dbHandeler {

    var $conn;

 public function __construct(){

        $this->initiatedb();

 }

    private function initiatedb(){

        //Details of the Databse
            $servername = "localhost";
            $username = "root";
            $password = "";
            $dbname = "xxxxxx";

            // Create connection
            $this->conn = mysqli_connect($servername, $username, $password, $dbname);

            // Check connection
            if (!$this->conn) {
                die("Connection failed: " . mysqli_connect_error());
            }else
               return $this->conn;

    }

 private function sql_query($query){

 }

}

Then I have donation.php and it extends the DB class

function __autoload($class_name) {
    include $class_name . '.php';
}

class donation extends dbHandeler{


    public function __construct(){

        $dbObj = new dbHandeler();
        $dbObj->initiatedb();
    }

    public function putDonation(){
        var_dump($_POST);

    }

    public function getDonation(){


    }
}

When I try to access the donation class I am getting following error

<br />
<b>Fatal error</b>: Call to private method dbHandeler::initiatedb() from context 'donation' in <b>C:\xampp\htdocs\templeform\api\donation.php</b> on line <b>13</b><br />

error
Vikram Anand Bhushan
  • 4,836
  • 15
  • 68
  • 130

2 Answers2

6

The "private" access specifier is meant to be available within the class it is defined only, you cannot call it from outside the class it is defined in, even from a child class. You can maybe use the "protected" access specifier instead which will be available to the child classes as well but not the other classes. Hope this helps.

Vishnu Nair
  • 2,395
  • 14
  • 16
0

If the method is private, there is a reason, why the method is private. A private functions could only be called inside the class. If the method should be available in inherited classes, you should mark the function protected. If the function should be accessible from everywhere, it must be public.

If you want to change the accessibility of the function, you could do so with ReflectionMethod::setAccessible - but doing this is most often a good indicator for a bad design.

$method = new ReflectionMethod('dbHandeler', 'sql_query');
$method->setAccessible(true);

If you dont want to change the accessibility, you could also use reflection to invoke the method directly, which might be the better option.

Nevertheless you should really think about you design. If this is your own class, why don't you just mark the function public or protected?

Philipp
  • 15,377
  • 4
  • 35
  • 52