Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228
A Quick Guide To PHP Types

Comments Blog About Development Research Sites

A Quick Guide To PHP Types

Feb 11, 2008
One of the aspects that make PHP such an easy language is its ability to convert almost any data to the type required. Downside of this is that you can never be too sure about what type your data actually is. In itself not a real problem, but it can lead to some unexpected results.

After a post on a forum about this I decided it might be time to elaborate a bit more on what types PHP actually has, what they can do and how you can enforce / detect them. A tip for managers: if you are interviewing for a PHP programmer, ask your candidate to name at least 6 different types. If they can't, chances are he or she isn't really all she's cracked up to be.

PHP's types:
Letst start off with a listing of all the types available. First off, all the scalar types:
Boolean
Integer
Float
String

Next, the compound types:
Array
Object

Lastly, the special types:
Resource
NULL

What can these do for you?
Booleans: true / false. Booleans are the perfect way to ascertain a condition. I often see people returning 0 or 1, as they are used to do so in C and C++. PHP's true and false are, contary to common believe, not integers! A quick example to demonstrate:
Code (php) (nieuw venster):
1
2
3
$bool = true;
$int  = 1;
echo
$bool === $int ? 'True' : 'False'; // Echo's false.


Note the special type comparison operator '===' - more on that later.

Integers: any real number, negative or non-negative. If you want a number, do not enquote it since then it is automatically cast to a string! Integers are almost seemlesly cast to strings and floats and vice versa so do not worry too much about them; it's mostly a performance issue.

floats: these can cause some serious headaches. Floats are not really just int's with a comma in them - they have a floating comma (hence the name). As a result, they tend to loose precision, especially with very big or very small numbers. A detailed examination of this behaviour is available on wikipedia. For now, let me make just one point clear: never EVER use floats for monetary data!

Yes, I know, floats seem like the perfect type for currency data, but take it from me: NEVER use them for important calculations unless you absolutely have to! When monetary data is concered, instead go for either a decimal (not available in PHP) or instead represent values in cents with integers. A third, less common aproach is to use 2 integers (one for cents, one for whole amounts). Decide for yourself which one suits your application best, just DO NOT EVER use floats. Seriously, I cannot stress this enough.

Strings: are not just a pretty way to cover a girl's ass, they are also the main datatype in PHP. Main, in this case, because almost all data is converted to it at some point or another. Internally they are arrays of 8-bit characters with no fixed length which means you can put as much data in them as you wish. The only big drawback about strings in PHP is that they have, as of yet, no native support for unicode - seldom a problem, but a usefull fact to keep in mind.

The compound types:
Compound types are really just containers for other types. With array's these containers are quite straightforward, with objects slightly less so, but more on that later.

Arrays: Can be n-dimensional and contain both strings and integers as keys. Floats are truncated to strings according to the manual, but I doubt anyone in their right mind would want floats as array indici anyway so that's allright. One of my favourite things to do with array is iterate over their values by reference. This is basicly the same as using array_walk but with a much shorter syntax:
Code (php) (nieuw venster):
1
2
3
4
5
6
7
8
$array = new Array('a' => 'some value', 'b' => 'Other value');

foreach(
$array as & $item)
  $item = strrev($item);

echo
$array['a']; // Outputs 'eulav emos'

$array[] = 'New value';

Those who understand references will see directly why this works. Those who don't will just have to google it or wait for me to write an article on them ;)

The last line of this example shows another nifty little trick with arrays: if you assign a value to an undefined array index using [] it is automatically appended to the array - exactly the same as with array_push, but with a lot less code. Note that, since we do not assign an index, it is automatically indexed at (highest_index_number + 1). Since we had no numeric index in our array, this means 'New value' is now at key 0.

Ojects: these are perhaps the most difficult to understand, and most versatile to use. I could write an lengthy article about them and barely scratch the tip of the iceberg - so I will leave that for a future date ;)

Special types:
PHP's special types tend to remind me to a remark Kyron used to make about 'special yellow bus'. Ie, the schoolbus for retards. The special types are usefull in their own right, but you will probably very, very seldom manipulate them since they tend to be a closed link to an internal PHP object.

Resources: these can generally only be used in the same context they are created. Databaselinks are resources (and evaporate at the end of your script), as are file handlers and many more. You can generally only use them in functions of the same class (mysql_query on a mysql link resource for instance) and a var_dump of them is usually as descriptive as a chineze instruction manual translated into english by a blind korean. One noteworthy thing about resources is that they are generally quite costly and if you want to use the same type of resource later on, it won't hurt to encapsulate them in a singleton pattern.

NULL: void. Emptyness. Nothingness. NULL isn't anything, it can't become anything and you can't append anything to it. If you create a variable without assigning a value to it a var_dump will show you it's NULL. The only use I find for it is in function argument lists as default value: if a flag can be either true, false or NULL you can easily check for it with isset. This brings me to the more usefull portion of this post:

Actually Using PHP's Types:
Many users think PHP does not support typehinting. In fact, it does, quite elegantly, but only to a certain extend: you can only hint at arrays and objects. What am I gabling about? Allow me to demonstrate!
Code (php) (nieuw venster):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function someFunction(array $array, SomeClass $object = NULL) {
  echo
"Hello world!";
}

class
SomeClass {
}

class
ExtendingClass extends SomeClass {
}


$array  = array();
$object = new SomeClass;
$extend = new ExtendingClass;

someFunction($array, $object); // This works fine!

someFunction($array, 'test');
// Error: Catchable fatal error: Argument 2 passed to
// someFunction() must be an instance of SomeClass


someFunction($array, $extend); // Extended classes also work!

Long story short: if you want to be sure your function only gets given an array or an object, you actually can enforce this! Unfortunately, type-hinting for strings and integers is not supported, though one can always dream of course.

Alright, so now your function requires an array to work, say we have a string, how can we make sure it won't start throwing exceptions? Simple, type-casting! Now I hear you thinking "didn't PHP do all our casting for us?" and you would be right. Normally PHP detects the type required by a PHP function and casts. However, it cannot detect the type required by userfunctions (well, not really anyway) and sometimes a little manual casting is in order.

There are several ways of going about this: one elegant, the rest ugly. You decide which is which:
Code (php) (nieuw venster):
1
2
3
4
5
6
7
8
$string = 'This is a string';

$array = (array) $string; // One

settype($string, 'array'); // Two
$array = $string; // Two

$array = array($string); // Three

Anyone with a C background will probably not have long too choose I think. The beautifull thing about (type) [data] is that it also works for most of the other types:

Code (php) (nieuw venster):
1
2
3
4
5
6
$string = 'This is a string';

$array  = (array)   $string; // array('This is a string');
$bool   = (bool)    $string; // true
$object = (object)  $string; // StdClass object with scalar 'This is a string'
$int    = (int)     $string; // 0. Ints are special.

String to int conversions are special in that only the first numeric entries in a string are considered for conversion. This is in my opinion somewhat strange behaviour, but the alternative would be to use the char-codes instead which would seem even more weird. To prevent problems with this, see one of my first points: do not use quotes around ints so they won't get cast to strings!

Now, I mentioned at the beginning I'd explain the '===' comparison operator. It is really quite straightforward. Everyone with some PHP background knows that '==' lets you compare two values. Using the '===' operator, also the type of the values is taken into consideration. Effectively what this means is the following:
Code (php) (nieuw venster):
1
2
3
4
5
6
7
8
9
10
11
12
$string = '25';
$int    = 25;

echo
$string == $int ? 'True' : 'False';
// True, strings are ints..?

echo $string === $int ? 'True' : 'False';
// False, of course they aren't!

// So what are they?

var_dump($string); // string(2) "25"
var_dump($int);   // int(25)

var_dump is particularly usefull in that it, as opposed to print and echo, also tells us what type a given variable is. He has a usefull brother called var_export which might also be worth looking into if you didn't know him already.

I could go on and on but frankly I do have better things to do, so keep an eye out for my next articles which, might or might not, be about objects, types and the last episode of the Sarah Conner Chronicles! ;)

FragFrog out!

New comment

Your name:
Comment: