Jump to content

Object Oriented Programming Issue


Kev0121

Recommended Posts

Hello, well ive created a database class which has simple mysql functions like, query, numrows, fetch_array and ive created a new class in a seperate file called users and i created a new instance of the database class

 

$db = new Database();

 

but when i use it in my user class it doesnt work, for example

 

require_once 'database.php';

class User {
var $user;
var $pass;

function select_a() {
	$sql = "SELECT * FROM users";
	$res = $db->query($sql);
}
}

 

Helllp please =D

 

/Kev

Link to comment
https://forums.phpfreaks.com/topic/154563-object-oriented-programming-issue/
Share on other sites

encapsulation...

 

methods and properties of your class belong to that class - anything declared outside must be passed in...

 

<?php
require_once 'database.php';

class User {
var $user;
var $pass;

        private function User($db)
        {
            $this->db = $db;
        }

function select_a() {
	$sql = "SELECT * FROM users";
	$res = $this->db->query($sql);
}
}

$user = new User($db);
?>

 

 

 

if you have php 5 available then you could use __construct() - it wold also be beneficial to make the database object a singleton class that way you won't have lots of instances of he 'same thing'...

 

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.