user656925
user656925

Reputation:

What is a PHP method for multiple inheritance? - excellent

I have a class that needs access to two other classes. Signin needs access to Post, and Signin needs access to Database. How do I do this?

I had previously made the inheritance chain linear, but this seems to confuse people as a Post is not a Database.

Upvotes: 0

Views: 66

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270607

PHP does not have multiple inheritance (as I think you understand already). If you cannot make a linear inheritance chain, another option is create and implement an interface:

class Child_Class extends Parent_Class implements Brother_Interface {}

However, that doesn't seem to fit your situation either.

For your needs, it my be appropriate to pass the Database object and the Post objects into the Signin object via dependency injection. After all, is Signin really an extension of Database? Is it an extension of Post (maybe). Dependency injection may be a more appropriate OO methodology here.

class Signin {
  private $db;
  private $post;

  public function __construct($post, $db, $othervariables...) {
    $this->db = $db;
    $this->post = $post;

    // Rest of constructor
  }
  // Access via $this
  public function something_using_db() {
     $this->db->execute("SELECT * FROM tbl;");
  }
}

How it is used:

$db = new Database();
$post = new Post();

// Create Signin object using the Database and Post    
$signin = new Signin($post, $db);

Upvotes: 3

Related Questions