Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP inheritance question regarding extended classes

If I got two classes extending a 3rd classs will the content of the 3rd class be instantiated twice when instantiating both, the 1st and 2nd class?

Example:

class class1 extends class3{}

class class2 extends class3{}

class 3{
    $this->db = new mysql();
}

$class1 = new class1();

$class2 = new class2();

On the example above will the db object be created two times? , on this case, resulting in 2 connections to mysql?

Thanks,

like image 857
Henrique Avatar asked Aug 12 '26 21:08

Henrique


2 Answers

There are several fundamental syntax errors with your example, but yes, a derived class contains the base class as a subclass, and so each instance of any derived class will contain all the members of the base class as well.

If the base class opens the connection to the database (but this requires you to write some non-trivial code, like a constructor), then this will happen in any derived instance:

class Base
{
  private $db;  // maybe "protected"...
  public function __construct() { $db = new mysqli; /* + connect! */ }
}

class Der1 extends Base
{
  public function __construct() { parent::__construct(); }
}

// etc.
like image 52
Kerrek SB Avatar answered Aug 15 '26 10:08

Kerrek SB


first,

class 3{
     $this->db = new mysql();
} 

would not run as there is a syntax error. you can't have code in a class unless it is in a method. I assume you meant the object creation line to be in the class constructer method __construct(). In this case the code would be run each time any of the classes were instantiated. this is unless of course you have overwritten the method in one of the entended classes.

like image 38
dqhendricks Avatar answered Aug 15 '26 10:08

dqhendricks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!