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
https://forums.phpfreaks.com/topic/135353-beginner-oop-some-questions/
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;

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.