[Lecture] eXtreme Programming - Richard Buckland

Tutorials on PHP, databases and other aspects of web development. Before posting a question, check in here to see whether there's a tutorial that covers your problem.

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

[Lecture] eXtreme Programming - Richard Buckland

Post by Benjamin »

minorDemocritus
Forum Commoner
Posts: 96
Joined: Thu Apr 01, 2010 7:28 pm
Location: Chicagoland, IL, USA

Re: Tutorials - [Lecture] eXtreme Programming - Richard Buck

Post by minorDemocritus »

For those of you that don't know, PHP also has assert statements. They work a bit differently from C assertions. Please correct me if I'm wrong with any of this... I just discovered it after watching the video :mrgreen:

First off, the manual pages:
[url=http://php.net/manual/en/function.assert.php]assert()[/url]
[url=http://php.net/manual/en/function.assert-options.php]assert_options()[/url]

The general usage is that you configure assertions with assert_options(), and make an assertion with assert(). I've created (read: stolen) the following code so I can include it in my scripts.

filename: assertions_inc.php
[syntax=php]<?php
// Sets assert_options
// http://www.php.net/manual/en/function.a ... ptions.php
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_WARNING, true);
assert_options(ASSERT_BAIL, true);
assert_options(ASSERT_QUIET_EVAL, false);
assert_options(ASSERT_CALLBACK, 'assert_handler');

// Sets callback function for asserts
// http://php.net/manual/en/function.assert.php
function assert_handler($file, $line, $code) {
echo "<hr /><p style='font-size:2em;color:red;'>Assertion Failed:
File: '$file'<br />
Line: '$line'<br />
Code: '$code'<br /></p><hr />";
}
?>[/syntax]

And say I want to debug the following code. (It keeps giving me this odd NAN thing...) :banghead:
[color=#0000FF]EDIT: Rather, it SHOULD give me NAN... but it just gives $root = 0... odd.[/color]

filename: sqrt_fun.php
[syntax=php]<?php
$foo = 5;
$bar = 11;
$square = $foo - $bar;
$root = sqrt($test);
echo "The square root of $foo + $bar equals $root.<br />";
var_dump($root);
?>[/syntax]

I can add assert statements to help figure out what the problem is.

filename: sqrt_fun2.php
[syntax=php]<?php
include 'assertions_inc.php';
$foo = 5;
$bar = 11;
$square = $foo - $bar;

// first assertion
assert('
$foo + $bar == 16;
');
// second assertion
assert('
$foo > $bar;
');

$root = sqrt($test);
echo "The square root of $foo + $bar equals $root";
?>[/syntax]

The first assertion I make is OK, so nothing different happens for that part. The second assertion is obvously wrong, so assert() stops execution (because of the options I've set) and displays the error. Oops, I meant to add those two numbers, not subtract!
Post Reply