[RESOLVED] OOP Question

admin

Administrator
Staff member
Hey guys. I've been struggling with this for a few hours now. Basically, here's what i want to do (it's really quite simple):

I have a class myClass and in it are functions. I'm deconstructing it and making it more accessible by only using functions for what they're used for and nothing else. i.e.

<?php

class myClass
{
var $dir;
var $error;
var $output;
var $files;

function get_files(){
// This function gets all the files in a directory
// If error, throw_error('Error', 'Message') is called
if(!$handle){ throw_error('Error', 'Can\'t open the directory!'); }
}

function throw_error($err, $msg)
{
$this->error = $err.'<br>'.$msg;
return $this->error;
}
}

?>

Unfortunately this doesn't work. I am wondering how i can call a function from within the same class so I don't have to use the outside script to do it. LIke:

$m = new myClass();
$m->get_files();
$m->throw_error('','');

Any ides? I know about using teh parent class, but I don't have a parent class, I have just one class. Any ideas would be hlepful.

~Brettyou need to use $this-> to let php know the method is contained within the class. also, you want to make your throw_error() method not return anything, just let it echo your error. otherwise your going to need to call it from outside.

function get_files(){
// This function gets all the files in a directory
// If error, throw_error('Error', 'Message') is called
if(!$handle){ $this->throw_error('Error', 'Can\'t open the directory!'); }
}

ps: (this looks like php4 code, but your in the php5 forum) if your using php5 there are much better ways of handling errors. check out exceptions.Thanks Thorpe. I had tried that. Let me explain my thinking here:

I have my php file that includes/requires the process.php page. process.php has the class structure in it. I want to return the error because in the index.php page, I will either echo it, or store it in a variable and echo it later. So is there a way I can do that, or do I have to echo it?

I know it's php4 code, I'm kind of writing half and half. I was unaware of the exception handling in php5, thanks for that. I use php5 on my personal box, but no web hosts have php5 installed yet so I can't use it, but I wanna learn it. So I'm going back and forth.

~Brettwell, if its going to return something, you need to store that returned value somewhere. otherwise where is it going to return to? you would be best to just have get_files return false on failure, then handle the error outside. ie;

$m = new myClass();
if (!$m->get_files()) {
echo "getfiles failed";
}

of course there are probably still better ways of handling this, and of course exceptions would be great. but yeah, we cant always use them.Okay, thanks. Works like a charm!!

~Brett
 
Back
Top