Try to understand extending classes

I try to understand the principle of extending a class with another class:

To test if I understand the principle I created two classes. One called PDO:

class PDO {  
    protected $pdo;
            
   function __construct($pdo) {
       $this->pdo = $pdo;
   }
}

and one called Login

class Login extends PDO {
    function username_exists($username) {
        $sql = "SELECT user_id
                  FROM users
                 WHERE username = ?
                 LIMIT 1";
                 
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(array($username));
        
        return $stmt->fetchColumn();
    }    
}

I use spl_autoload_register to load the different classes.:

require_once "connect.php";

function auto_loader($file){
    require 'classes/' . $file . '.php';    
}
    
spl_autoload_register('auto_loader');
                
$login = new Login($pdo);

When I include config.php (holding spl_autoload_register) in a page and run it I get the following warning:

Warning: PDO::__construct() expects parameter 1 to be string, object given in

Can someone please tell what I am doing wrong?

Thank you in advance

Hi Donald,

You’ll have to choose a different name for your base class, or use namespaces. The class PDO is already defined (assuming you have the PDO extension installed) and so PHP won’t allow you to define another class with the same name within the same namespace.

Hi fretburner.

Thanks a lot for that info. :slight_smile: I will try that right away

Your classes are not really an example of good inheritance, since you could better solve the problem you’re describing with dependency injection, i.e., just pass the PDO instance to a new Model, not let the model extend some PDO class.
Usually with inheritance we write classes where something is really the same as another, but has more or (partially) different functionally. So for example you may have a Customer class and a VIPCustomer class, where VIPCustomer extends Customer and is mostly the same but overrides, let’s say, the calculateDiscount method because they always get a better discount than regular customers. Then in the code in every spot where you should supply a Customer you can also supply a VIPCustomer and the code using the object would be none the wiser. The other way around, a method that expects a VIPCustomer cannot be passed instance of a regular Customer because VIPCustomer may have certain behaviour/methods that Customer does not have.

Hi ScalioXTX. Thanks for the answer. I’s really appreciated.