Jump to content

How do include a class inside of a class


Dat

Recommended Posts

How do i use a class inside of another class?

 

I have class blogPost and class database.

 

How do i use database inside class blogPost

 

class blogPost

{

include ('database');

$db = new database;

}

Link to comment
Share on other sites

class blogPost
{
  private $_db;
  public function __construct($db)
  {
    $this->_db = $db;
  }
}

include ('database');
$blog = new blogPost(new database);

What if i already have a __construct?

Link to comment
Share on other sites

Then pass the parameter to do that to the construct or create a method

  public function setDatabase($db)
  {
    $this->_db = $db;
  }

 

Although if $this->_db is vital for the blogPost class (which I suspect it is) it belongs in the construct.

 

 

As a few hopefully constructive tips..

 

tip #1

PHP(5) supports type hinting so this works as well:

__construct(database $db)

The more strict you can get the better imo. (Als provides more useful errors when you pass in a parameter of the wrong type)

 

tip #2

You may want to stick to the general PHP (and java and probably other programming languages as well) code convention to start classnames with a capital letter, so Database and BlogPost instead of database/blogPost.

 

(this is gonna be a rather late reply.. left this open in a tab for half a day)

Link to comment
Share on other sites

include ('database');
class blogPost
{
  function __construc() {
$this->db = new database();
}
}

 

That's not such a good idea, because now the blogPost object is tied to a specific database object.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.