user3425731
user3425731

Reputation: 3

PHP superclass's construct does not work in subclass

I have a problem with the inheritance of a __costruct() method in php. This is my super class:

class MyDataMapper
{
    private $connection; 
    function __construct()
    {
        $this -> connection = new mysqli($HOST, $DB_USER, $PASS, $DB_TABLE);      
    }
    //other methods...
}

I need to use a new class that extends the one above, and so this is what I've done:

class DataMapperExtends exstends MyDataMapper
{
    function __construct()
    {
        parent::construct();           
    }
    //other methods...
}

But for some reason this does not work: I get a mysqli error that happens on a prapre statement of one of my SQL query (error: Call to a member function prepare() on a non-object). Like this one:

   <?php $stmt = $this -> connection -> prepare($query); ?>

I don't know why this happens, it seems like the connection isn't initialized. Don't think there are error in the subclass, if I write this:

   <?php
     class DataMapperExtends extends MyDataMapper
     {
        public function __construct()
        {
         //even if it does not make a lot of sense
         $this -> connection = new mysqli($HOST, $DB_USER, $PASS, $DB_TABLE);      

        }
     }
   ?>

everything works fine. There are error in my superclass?

Thanks!

Upvotes: 0

Views: 76

Answers (2)

faintsignal
faintsignal

Reputation: 1836

If you need something in your class to be inheritable to subclasses, declare it as protected, not private. Protected members and methods are accessible by subclasses (and also by parent classes). Private members and methods are only accessible in the specific class in which they are declared.

Upvotes: 1

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44864

Your variable connection is defined as private

private $connection; 

Private is only available within the class.

So for sub-classes to access that you need to have it protected

http://www.php.net/manual/en/language.oop5.visibility.php

Upvotes: 1

Related Questions