Forum Moderators: coopster

Message Too Old, No Replies

Custom Error Handler - How to Make One?

         

stormshield

2:48 pm on Nov 1, 2006 (gmt 0)

10+ Year Member



Hi all,

I'm trying to make an error basket - a thing where I can manually place errors and display them a given way. I was thinking about something like this:


class errors {
function array_create(){
$this->errors = array(); // creating an array
}
function add_error($content){
array_push($this->errors,$content); // adding an error

}
function display_errors(){
foreach( $this->errors as $display){
echo "Errors: " . $display . "<br>";
}
}
}

//However, the problem with that class is I cannot use it inside another class.

class someclass {
function somefunction(){
$error_22 = "File too big";
$errors->add_error($error_22); // a php error appears here ("Call to a member function on a non-object in ...")
}
}

$errors = new errors();
$errors->array_create();
$errors->add_error("an error");

$someclass = new someclass();
$someclass->somefunction();

$errors->display_errors();


I'd the output to be: "an error", "File too big"

Anyone knows a smart way to achieve that?

Thanks
Storm

coopster

7:13 pm on Nov 1, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You aren't using the other class correctly, that's all. Have a look at the Scope Resolution Operator manual pages for both PHP4 and PHP5. PHP4 probably explains the "how" in a little easier reading:
Scope Resolution Operator (::) PHP4 [php.net]
Scope Resolution Operator (::) PHP5 [php.net]

Psychopsia

8:26 pm on Nov 1, 2006 (gmt 0)

10+ Year Member



For 'errors' class, I would write it as:


class errors {
var $error = array();

// Adding an error
function add($str) {
$this->error[] = $str;
}

// Display errors
function display() {
foreach ($this->error as $str) {
echo "Error: " . $str. '<br>';
}
}
}

$errors = new errors();
$errors->add('An error');

...

$errors->display();

baze22

10:25 pm on Nov 1, 2006 (gmt 0)

10+ Year Member



Aside from a variable name different from the class name, you would have to define the errors object as global in the somefunction() function.

function somefunction() {
global errors;
// now you can access errors object
...
}

baze

stormshield

4:13 pm on Nov 2, 2006 (gmt 0)

10+ Year Member



OK, it works now... I had to use global and the Scope Resolution Operator.

Thanks!