OOP and PHP

Associate
Joined
3 Oct 2006
Posts
2,304
Location
London
Hi There,

Got a bit of an interesting one for you.

I'm having a go at writing my very own class. (Ooooo, ahhhhhh, etc.) What it's going to do is have three functions. One to grab some data from a database, a second to filter that data and a third to put the filtered data back into a different database.

To do all my database calls, I'm using ez sql and here-in lies the problem.

Ez sql makes a $db class, which contains various functions and variables all related to database type things. I want to have on 'global' $db instance for the whole of my class, but I can't get it to work.
Code:
<?PHP
require_once "db/ez_sql_core.php";
require_once "db/ez_sql_mysql.php";
		
class export_blog
	{

		var $grabbed;
		var $filtered;

		
		function __contruct()
			{
				$db = new ezSQL_mysql('driversv_oice','keepmoving','driversv_wrdp1','localhost');
			}
			
		public function grab()
			{
				global $db;
				$query = "SELECT * FROM wp_posts";
				$blogposts = $db->get_results($query);
				var_dump($blogposts);
				
			}
			
		public function filter()
			{
			
			
			}
			
		public function import()
			{
			
			
			}
	
	}
	
	
$test = new export_blog();
$test->grab();
?>

I can however, get it to work when I define an instance of the db class within the function. This works...

Code:
<?PHP
require_once "db/ez_sql_core.php";
require_once "db/ez_sql_mysql.php";
		
class export_blog
	{

		var $grabbed;
		var $filtered;
			
		public function grab()
			{
				$db = new ezSQL_mysql('driversv_oice','keepmoving','driversv_wrdp1','localhost');
				$query = "SELECT * FROM wp_posts";
				$blogposts = $db->get_results($query);
				var_dump($blogposts);
				
			}
			
		public function filter()
			{
			
			
			}
			
		public function import()
			{
			
			
			}
	
	}
	
	
$test = new export_blog();
$test->grab();
?>

Can anyone point me in the correct direction for what I want to do?

Many thanks,

Jon
 
Set it as a member variable of the class:
Code:
class export_blog
{
	[COLOR=Red]private $db;[/COLOR]
	
	public function __construct()
	{
		[COLOR=Red]$this->db[/COLOR] = new ezSQL_mysql('driversv_oice','keepmoving','driversv  _wrdp1','localhost');
	}
	
	public function grab()
	{
		$query = "SELECT * FROM wp_posts";
		$blogposts = [COLOR=Red]$this->db[/COLOR]->get_results($query);
		var_dump($blogposts);
	}
}

Also, since you appear to be using PHP5, you should usually mark class member variables as private so that they can't be accessed outside the class. Use accessor methods to get and set the values of them.
 
Last edited:
This OOP thing is pretty good. Wish I had put the time and effort in before!

I think I'm going to have to re-write some of my websites with it :D
 
OOP is great, but just remember not to get carried away - it has a time and a place. When I first learnt it I had a tendency to want to write everything in it, which was silly. :P
 
Back
Top Bottom