Ramblings of a web guy

Initializing & typing variables with settype()

Posted in PHP, Programming by Brian Moon on September 14th, 2006

These days, the way to develop is to have E_ALL and maybe even throw in E_STRICT if you are really hard core. That of course means having all your variables initialized before they are used. You could just do something like this:

<php

$var1 = 0;
$var2 = “”;
$var3 = 0.00;
$var4 = array();
$var5 = new stdClass;

?>

That works fine and is pretty clear. However, I think a more elegant solution is to use settype() like this:

<php

settype($var1, “int”);
settype($var2, “string”);
settype($var3, “float”);
settype($var4, “array”);
settype($var5, “object”);

?>

IMHO, this is much more clear. Its a standard way to set the type and default value of your variables. You see, settype() assigns a default value to the variables if they do not exist already.

Another handy use is in a function.

<?php

function myfunc( $someint, $somestring) {

settype($someint, “int”);
    settype($somestring, “string”);

if($someint>0){
        echo $somestring;
    }
}

?>

Now this example does not do much for the string, but it ensures the int variable is an integer. Without the settype() line, the if() statement would evaluate to true if some string value was passed in for $someint.

The one down side that some may not like is with arrays and objects. If the variable is a scalar type (int, string, float, boolean), it will be changed into an array/object with a member called scalar that contains the scalar value.

There is no note in the official docs (there is one in the comments) about settype initializing a variable. I think I will submit a documentation update request in the bug system. I am also considering writing a test to ensure this unknown, but IMHO very useful feature stays in PHP.

Phorum 5.1.16 Relased

Posted in MySQL, PHP by Brian Moon on September 6th, 2006

This is another bugfix release with only a couple of module-related new features.

The news for this release are:

* “fixed a bug with using the alternate search backend. database search was still done while it shouldn’t.”

* MFH: addon.php allows for addon scripts that are implemented using a module

* Added extra hook ‘posting_custom_action’ to the posting editor code

* MFH: Added signing of editor form data to prevent data tampering

* Added a simple general purpose private key based signature system

* redirect back to vroot if mark-read is used (fixing #403)

For users running 5.1.15 we recommend to replace at least search.php to lessen the load on searching. A couple of smaller fixes were also implemented therefore we recommend every user running phorum 5.1.x to upgrade to this version.

If you want to see the full changelog you can find it here http://www.phorum.org/changelog-5.txt

Comments Off