A Basic Class for Debugging - Features/Improvements?

Hello,

As my username denotes, I’m new to OOP concepts in PHP. I was reading an article recently about helper functions. As a skill development exercise, I’m creating a class that will contain several helper functions. My first method will assist with debugging code. I use this sometimes when I’m debugging code:


print "<pre>";
print_r($var);
print "</pre>";

So far, my class method solution looks like this:

class Helpers {
     private static $devStatus = 1; //0 for off 1 for on

     public static function devDump($blurb=null, $var) {
		// Check to see if we are in debug mode
		if (isset(self::$devStatus) && self::$devStatus==1) {
			print $blurb.": ";
			print "<pre>";
			print_r($var);
			print "</pre>";
		}
	}
}

Here’s how I use the above code:

$someArray = array("firstname"=>"Site", "lastname"=>"Point");
Helpers::devDump('$someArray', $someArray);

The output looks like this:

$someArray:

Array
(
    [firstname] => Site
    [lastname] => Point
)

My question is…Is this how you would do it? Any suggested improvements?

The only thing I tried to do, but couldn’t, is have the method print out the variable name being passed as the $var parameter. From what I tried and what I read with a Google search, PHP can’t do this yet. Is this true? In all of my Noob glory did I miss something? My primitive solution, in the code above, is to pass in the name of the variable as the first parameter and the value of the variable as the second parameter.

Is it ok to print text to the screen in the middle of a class like that?

Thanks,
OOPNoob

There are actually 3 separate calls to “echo” in that function… :confused:

I also have been using TDD for the last year or so in all my new code, and it indeed has helped tremendously in eliminating the need for trial-and-error “what’s in this variable?” hacks like these debugging variable dump functions. However, there are still times when functions like this are needed, so I still keep it around (or something like it) in all my code projects for when I need it. There’s no shame in useful functions that help you resolve problems quickly.

That’s my experience, too. I’ve been using TDD for quite some time now, and I have noticed the time you spend on debugging becomes increasingly less. Of course, that was one of the reasons I started doing TDD in the first place, so I’m not surprised. Nonetheless, there are situations where I am just to dumb to see what’s going on, and those are the times I start the debugger.

Well, I didn’t mean to say it’s a must, just saying that I find it helpful, and others might feel the same way.

Haven’t used a debugger in PHP for a long time, before PHP 5 for sure.

Though am tempted to write a pure JS/HTML5 debugger for PHP, as I now think it is possible without any ugly hacks. But this is more of an learning/experimenting with HTML5 WebSockets, and Node.js for the DBGp protocol/WebSocket proxy/adaptor thing.

Though trying to use the JS debugger with Safari/Chrome has slowly driven me mad, and that JS PHP debugger might not be that usable.

Though I don’t see why a debugging class can send messages out of band as it were, and indeed did toy with seeding debug messages using IM.

Hi…

Maybe. TDD killed off the need for this stuff except in C (seg faults) and Perl (confusing references).

For the last few years I’ve had the luxury of a good code base with very good test coverage. Except for some legacy stuff I haven’t needed to do any complex debugging.

I’ve recently changed jobs however…

yours, Marcus

Ehr… Perhaps it’s time to start knowing that? I have debugging methods like the ones you have just the same, I just don’t use them as intensive any longer. Dumping the content of a variable on the screen can be incredibly useful, but it doesn’t tell you anything about how that variable content came to be.

Obviously, developers have a mind too, so they can think about how the request went through the application and even debug_backtrace( ) if they can’t figure it out, but it’s much easier to say: “start debugging” and stepping through decision-making points of your application.

If you’re using an IDE, chances are that you can just point at “Debug” and click :wink:

Hello,

In regards to this thread, there is no real world issue. I’m still learning OOP and wanted to see if how I coded this very simple class was the “right” way. If there is such a thing. I’m really happy with the responses and the great suggestions. I’ve learned a lot. It’s nice to have such a great resource!

However, in the next couple of days, I’ll be posting a different thread regarding VO’s, DAO’s and Singleton database connections. That thread will have a real world issue. :slight_smile:

Before posting that thread, I need to search these forums to see if those topics have already been asked/answered. I’ll be shocked if they haven’t…

Thanks to all the responders,
Noob

---- (Marcus was faster)

Hi…

By default the callback is a function name. My versions above are functions, not class methods. If you have…


function p($x) {
    print '<pre>';
    print_r($x);
    print '</pre>';
    return $x;
}

function pp($someArray) {
    $xs = func_get_args();
    array_map('p', $xs);
} 

…without any classes, then all should be fine.

If you want to pass a method on an object as a callback, here is what you do…


class Multiplier {
    private $factor;

    function __construct($factor) {
        $this->factor = $factor;
    }

    function actOn($value) {
        return $value * $this->factor;
    }
}

$doubler = new Multiplier(2);
print_r(array_map(array(doubler, 'actOn'), array(1, 2, 3)));

A callback to an object is a two item array, the first item the object and the second item the function name.

If you want to call a static method…


class Doubler {
    static function double($value) {
        return 2 * $value;
    }
}

print_r(array_map(array('Doubler', 'double'), array(1, 2, 3));

Now the callback is a two item array, the first the class name and the second the static method name.

It’s clumsy, and all because OO was added to the language at quite a late stage. You don’t need to use array_map(), I was just trying to shorten the code a little (although array_map() is nice once you get the hang of it). array_map() is a functional construct, rather than specifically an OO one.

Frankly the examples here are a bit silly. You need something more complicated o make OO useful.

As for writing a debug class, that’s probably not a good idea. It’s too simple a job to require OO. Do you have a real world problem you’d like to solve. Maybe I can sugest some code for that.

yours, Marcus

Hello,

I’m trying to work through all of the great code suggestions. I’m doing so in an OOP fashion. When I try to use your code in my class, it gives me an array_map first element should be null or callback error. What am i doing wrong?


class Helpers {
     public $x;

     public function static p($x) {
          print '<pre>';
	  print_r($x);
	  print '</pre>';
	  return $x;
     }

     public function pp($someArray) {
	    $xs = func_get_args();
	    array_map(self::p($someArray), $xs);
     } 
}

$helper = new Helpers();
$someArray = array("firstname"=>"Site", "lastname"=>"Point");
echo $helper->pp($someArray);

The output I get is:

Array
(
[firstname] => Site
[lastname] => Point
)

Warning: array_map() [function.array-map]: The first argument, ‘Array’, should be either NULL or a valid callback…

What am i doing wrong?

My one beef with this is that it’s called “echoPre” but the function “echo” is never actually called. Misleading method name, in my opinion. :slight_smile:

Hi…

I certainly wouldn’t disagree with both your points.

Debuggers are probably a good thing, I just don’t know how to use them :(.

TDD is a bit much for a complete beginner if using a full on testing framework. The main thing is to have a separate file and check them in as part of your code. Once you do that, a homebrew solution will get you going…


t(this_should_give_three() == 3, 'Oh dear, not 3');
t(this_should_give_hello() == 'hello', 'Oh dear, not hello');

…where t() is…


function t($predicate, $message) {
    if ($predicate) {
        print "$message\
";
    }
}

One tip with print statements: print the thing and then immediately remove the statement. Once you get a nested trail of them you start to lose the plot and things take longer. It’s like an archeological dig and just as slow.

If you catch your self doing this, take a bit of the code that is causing trouble and create a small example with it. Once isolated you’ll find it much easier to deal with. The isolated part can become the germ of a test case later.

If you can’t isolate the code, then you have bigger problems :eek:.

yours, Marcus

p.s.


function pp() {
    $xs = func_get_args();
    array_map('p', $xs);
}

:slight_smile:

I find p() so neat that I’ve never needed a multi-argument one.

The problem with dumping objects/variables content is that you have to litter the code with those calls and you still see only a snapshot of something. With a debugger you can see the flow of the code, step by step how things are changing. It’s much easier.

TTD should help you too to prevent bugs but I think it’s too advanced for a beginner.

Here’s mine - takes an unlimited # of arguments - much more useful that way.


	/**
	 * Print out an array or object contents in preformatted text
	 * Useful for debugging and quickly determining contents of variables
	 */
	function echoPre()
	{
		$objects = func_get_args();
		foreach($objects as $object) {
			echo "<h1>Dumping " . gettype($object) . "</h1><br />\
";
			echo "\
<pre>\
";
			print_r($object);
			echo "\
</pre>\
";
		}
	}

Thanks for the book tip. I have a Safari Book subscription, I’ll start reading that tomorrow.

Thanks,
OOPNoob

Hi…

A real debugger is something that plugs into an IDE or has it’s own command line. Firebug (Javascript) is an example. You can single step through code, view variables, etc. I hardly use them myself :).

Most developers I know drop back to printing as a first step. I have this in a start up file set in the php.ini…


function p($x) {
    print '<pre>';
    print_r($x);
    print '</pre>';
    return $x;
}

A slightly more optimised version of yours. I can turn this…


hope_i_get_the_right_value(hope_i_gave_the_right_value());

…into…


hope_i_get_the_right_value(p(hope_i_gave_the_right_value()));

…to see what’s going on.

I should say I do a lot less debugging now that I’ve discovered unit testing. PHPUnit/SimpleTest are unit testing frameworks. Get a copy of “Test Driven Development by example” (Kent Beck) to get an idea of what it’s all about.

yours, Marcus

Hello,

I’ve heard of PHPUnit, but I’m not smart enough to figure it out…yet. Baby steps for me.

Is that what you meant by a real debugger?

Thanks,
Noob

Odd, I wish I could explain what I thought I’d read at that time. Perhaps I conflated echo with print. My apologies. :slight_smile: