Jump to content

Accessing another class from a class.


Peec

Recommended Posts

I started for a while ago to program with Object Oriented Programing.

 

I have yet not found out how to access my DB class from my own created class.

 

 

The DB class im using is: dbsimple. ( have not bothered to create my own db class ).

 

 

Here is an example:

 


// I create an instance of DB class with this:
$DB = dbsimple_Generic::connect("".$db['db_type']."://".$db['db_username'].":".$db['db_password']."@".$db['db_host'].":".$db['db_port']."/".$db['db_name']."");
// Now i can use $DB->query("") here, but i cannot use it wihtin my class without the GLOBAL scope.
class myclass{
  function blah{
    $blah = true;
    if ($blah == true){
        global $DB;
        $DB->query("INSERT INTO `Db` (`h`,`s`) VALUES ('1'.'2')");
    }
  }
}

Link to comment
Share on other sites

You could pass it to your class constructor or the method where it is needed. You could also look into the singleton or registry pattern.

 

Singleton

<?php
class SingletonTest
{
static private $instance;

// private constructor to enforce the usage of SingletonTest::get_instance()
private function __construct() {}

public function get_instance()
{
	if(!(self::$instance instanceof self))
	{
		self::$instance = self;
	}

	return self::$instance;
}

public function test()
{
	echo "Hello World";
}
}

$obj = SingletonTest::get_instance();
$obj->test(); // output: Hello World
?>

 

Registry

Note that the registry here uses a singleton.

<?php
class TestClass
{
public function test()
{
	echo "Hello World";
}
}

class Registry
{
private static $registry = array();
private static $instance;

private function __construct() {}

public static function get_instance()
{
	if(!(self::$instance instanceof self))
	{
		self::$instance = new self;
	}

	return self::$instance;
}

public function set(&$item, $name = null)
{
	if(is_object($item) && is_null($name))
	{
		$name = get_class($item);
	}
	else if(is_null($name))
	{
		throw new Exception('Non-objects must have a name');
	}

	$name = strtolower($name);

	self::$registry[$name] = $item;
}

public function &get($name)
{
	if(self::exists($name))
	{
		$name = strtolower($name);
		return self::$registry[$name];
	}
	else {
		throw new Exception("The item '{$name}' does not exist in the registry");
	}
}

public static function exists($name)
{
	return array_key_exists(strtolower($name), self::$registry);
}
}

$obj = new TestClass();

$registry = Registry::get_instance();
$registry->set($obj, 'test');

//...

$registry = Registry::get_instance();
$obj = $registry->get('test');
$obj->test(); // output: Hello World
?>

 

 

You could then use an autoloader so you don't have to use include/require every time.

Link to comment
Share on other sites

Never, ever, do this.

 

class myclass{

  function blah{

        global $DB;

    }

  }

}

 

You'll see this type of coding in pieces of junk like Wordpress and MediaWiki, that doesn't make it good practice. It makes your code hard to understand structurally, and hard to maintain.

 

Simply create your DB object and pass it as an argument. Something like this:

 

class MyClass {

private $db;

public function __construct(dbsimple_Generic $db){
	$this->db = $db;
}
public function blah(){
	$this->db->query("INSERT INTO `Db` (`h`,`s`) VALUES ('1','2')");
}
}
$myObject = new MyClass(
dbsimple_Generic::connect(""
	.$db['db_type']."://".$db['db_username'].":"
	.$db['db_password']."@".$db['db_host'].":"
	.$db['db_port']."/".$db['db_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.