Jump to content

Beginner OOP - Some questions


Parhs

Recommended Posts

Hello to all ;D

First of all sorry for my English.

Although i have programming experience i havent used object oriented design a lot.

I know what are classes inheritance etc but i amnt sure wether i do things correctly..

Where should i start? Some books i found didnt help a lot..I want to see real examples,how others program in OOP.

Also i am thinking to make a project in PHP using OOP and i am unsure how to do things.

For example one simple question i have..

Suppose that i have a Database class which has some methods to retrieve and send data to database.And suppose that i have a News and Users class. Suppose i have some functions News->getNews(blabla)  Users->getUserInfo(blabla) ...

The question is.. Should i create a database object

$database=new Database();

and pass this instance of the object at the News or Users class?

e.g  getNews(blabla,$database)

Or

getNews() should create a Database instance object ?

I cant find any answer on this please help!

Link to comment
Share on other sites

Its entirely up to you. There are no fixed rules for OOP. The concept of OOP is about reusability, so could you use the user class in another project by itself or is it coupled tightly to your db object (i.e. would you have to take both). If you want to use the db object in you user class then why not extend it i.e (using a made up database object).

 

class user {
  public $name;

}


class dbUser extends user {
  private $db;

  // pass a new db object in
  public function __construct(db $db) {
    $this->db = $db;
  }

  public function getUser($id) {
    $this->db->query("SELECT * FROM user WHERE id='".$id."'");
    $result = $this->db->record();
    $this->name = $result['name'];
  }
}



// usage
$user = new dbUser(new db());
$user->getUser(12);
print $user->name;

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.