3

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,

3 Answers 3

2

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.
Sign up to request clarification or add additional context in comments.

Comments

1

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.

5 Comments

yes, was trying to illustrate only but Im aware of the syntax errors. Thanks for the clarification. So, seems its not a smart idea to have the db class in the base class that will be extended if more than one class will extend it on the same application.
@Henrique you could place the object in a static property (only if that property is currently null), which would ensure a single instance of the db class and only one initialization.
Sorry for the dumb question, but how that would be? declare 'protected static $db'? The rest gonna remain the same? $this->db = new mysql(); ... ? Thanks,
@Henrique the rest would be more like if (self::$db === null) self::db = new mysql();
Gotcha, I will play with that. Thank you.
0

if new mysql() creates a connection, yes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.