
Custom Classes – Iterator + Container
This article covers making a custom iterator type container in PHP. When I talk about a “container” I mean a class that holds something, often in a similar was that an array does. Adding iterator capabilities to it means it will work with a foreach statement like an array does too, and once you complete it you will then be able to add custom functionality to the class that goes beyond what an array can do. (You will need PHP 5+ to use this code.)
I’ll just show you the whole class, and you can take a look and try to grasp what is going on.
class container implements Iterator{
private $var = array();
public function __construct()
{
}
public function set($value, $key=-1)
{
if($key == -1){
$this->var[] = $value;
}else{
$this->var[$key] = $value;
}
}
public function delete($key)
{
unset($this->var[$key]);
}
public function get($key)
{
return $this->var[$key];
}
public function count()
{
return count($this->var);
}
public function rewind()
{
reset($this->var);
}
public function current()
{
$var = current($this->var);
return $var;
}
public function key()
{
$var = key($this->var);
return $var;
}
public function next()
{
$var = next($this->var);
return $var;
}
public function valid()
{
$key = key($this->var);
$var = ($key !== NULL && $key !== FALSE);
return $var;
}
}
The class is just based on the standard example from the PHP manual. It is different however, it allows you to set and get (and unset) variables in the array that is inside the class. In a way this is a wrapper for an array, rather than inheriting from an array or fully duplicating an array’s capabilities. The class does inherit from the Iterator class.
The functions rewind(), current(), key(), next(), and valid() are what make the iterator capability work. We don’t really have to have them defined this way if we inherit from the right class, but I wanted to show them defined because it would allow you to create custom behaviors there in the future. That’s the point of this class. As it is it is just an inferior version of an array, but once you start customizing it the possibilities are endless.
Next we just test it and get familiar with using it.
$mycontainer = new container();
$mycontainer->set("Cats", 9);
$mycontainer->set("DOGS", 90);
$mycontainer->set("Rats", 900);
foreach($mycontainer as $key => $value){
echo "$key :: $value \n";
}
Exactly as you probably thought it would work, 3 halues are set and 3 are printed. The second parameter of set() is the key, which can be omitted. The next example does not use the iterator part of the class but note that it basically doesn’t work if you use the second parameter of set. It is only functional in the following manner.
$mycontainer = new container();
$mycontainer->set("Cats"); //with second parameter omitted this is key 0
$mycontainer->set("DOGS");//1
$mycontainer->set("Rats");//2
for($i = 0; $i < $mycontainer->count(); $i++){
echo "$i :: " . $mycontainer->get($i) . " \n";
}
That should have printed the same values as before but with the keys 0, 1, 2. Now you can see why the iterator is usefull for anything that does not use completely continuous numeric keys. Even using $mycontainer->delete(1); would throw off the for() loop.
Now that you have a class and know how to use it, try to think of ways to make it useful. There are many possible features that a container class could have:
Sorting
Searching
Hashing
Type Checking
Error Checking
Checking for duplicates
Limited Sizes
Variable iterator start and stop indexes
Variable type returns like choosing to iterate as float or int
Efficiency in speed or by using less memory
Constants, and why they are used
In programming, a constant is anything that is supposed to be the same all the time and cannot be changed. Basically is is that way at least until the program starts again. In PHP constants are not similar to variables in syntax, which is in some ways a surprise. I’ll quickly show you a C constant and then a PHP constant.
constants in C:
const int AARDVARK = 2;
constants in PHP:
define(‘AARDVARK’, 2);
normal variables in PHP:
$AARDVARK = 2;
So the first thing to keep in mind is that constants are defined and used a bit differently than variables in PHP.
define('MAXIMUM', 500);
if($amount > MAXIMUM){
die("amount was greater than maximum!");
}
That example pretty much sums up normal constant usage. If somehow we didn’t know if the constant was set yet we could do something like this.
if(defined('MAXIMUM') == false)
define('MAXIMUM', 9999);
if($amount > MAXIMUM){
die("amount was greater than maximum!");
}
Back to the first concept, why choose to make something a constant rather than a variable. It’s often intended to be a technique to minimize bugs, even though the bugs would be caused by the programmers. It’s just safer to have a value that cannot be edited rather than one that can but will cause problems if it is. There are also reasons like clarity, separating regular variables visually from constant data. In PHP constants are also super globals, similar to $_POST for example, they can be used anywhere once defined. All the more reason that you cannot set a constant to a different value, since you have global access to it. Predefined Constants are another major part of PHP as they handle a lot of things specific to various areas of PHP without taking up variable names. For example the MySQL module in PHP has a lot of constants that are defined before your script runs.
Let’s try to answer some questions that may come up…
Going Retro With PHP – A Hits Counter Step By Step
Going Retro With PHP – A Hits Counter Step By Step
It wasn’t all that long ago that the web was littered with little “number of visitor” indicators. The point of these was either to show how popular your site was, or more likely just because the site owner had no administrator level site statistics program running. Now most sites have a sophisticated statistics system or other means of counting visitors and these visible counters have become less popular. It will still be a good learning experience to try making a script for counting visitors from scratch.
A simple function to detect a valid page load might look like this
function log_page_load(){
$invalid_list = '/(googlebot|crawler)/i'; //set a regular expression that detects invalid agents like googlebot
if (preg_match($invalid_list, $_SERVER['HTTP_USER_AGENT'])){
// it is a bot
}else{
// it is probably a browser
}
}
As you can see we are erring on the side of caution, making browsers the default for most possible strings. That is because there are probably countless possible browsers now with cell phones and other devices included. There’s no easy way to tell bot from human computer user there may be no perfect method that is always right. There definitely are techniques that are pretty accurate compared to what I show above but they are beyond the scope of this article.
Once we have decided the request is a real pageview we can get on with the reading and saving of data.
$filename = "counterfile.dat";
if(file_exists ($counter_file)){
$counter_file = fopen($filename, 'r+');
$total_count = trim(fread($counter_file, filesize($filename)));
}else{
$counter_file = fopen($filename, 'w');
$total_count = 0;
}
//other code here
...
//save file
ftruncate($counter_file,0);
fwrite($counter_file, $total_count);
fclose($counter_file);
First we opened the file, but since it may not exist we check that, and create it if it doesn’t (opening with w will do that). Otherwise it should work fine to read it. To save it we erase it (ftruncate($counter_file,0)) and write new data, which is just a number. In the next example let’s combine all that we have covered.
function log_page_load(){
$filename = "counterfile.dat";
if(file_exists ($counter_file)){
$counter_file = fopen($filename, 'r+');
$total_count = trim(fread($counter_file, filesize($filename)));
}else{
$counter_file = fopen($filename, 'w');
$total_count = 0;
}
$invalid_list = '/(googlebot|crawler)/i'; //set a regular expression that detects invalid agents like googlebot
if (!preg_match($invalid_list, $_SERVER['HTTP_USER_AGENT'])){
//it is a brower. probably. increment and save.
$total_count++;
ftruncate($counter_file,0);
fwrite($counter_file, $total_count);
}
fclose($counter_file);
if(!trim($total_count))
$total_count = 0; //let's make sure it is a 0 if it somehow was set to a blank string
return $total_count;
}
echo "val= ". log_page_load(); //each load you get 1, 2, 3, 4
so there you have it, define the function and either capture the return value for later or print it as shown.
Isn’t there something missing though? Most of the counters are graphical since they are used on sites that have no scripting. How can we get graphics instead of just numbers as a text string? There are many ways, but try this on for size.
$page_loads = log_page_load(); //logs once and also return the new value
$page_l_str = strval($page_loads);
$icons = "";
for($i = 0; $i < strval($page_l_str); $i++){
$icons .= '<imr src="images/' . $page_l_str[$i] . '.gif" />';
}
echo $icons;
that will produce image tags with the pattern <imr src=”images/1.gif” />Â and so on. $page_l_str[$i] means get the letter with index $i.
Of course you might also wish to zero padd it or instead of images use <li>$page_l_str[$i]</li>, there are a limitless variety of possibilities with modern css and php.

To take this a step further you might want to build in counting of visitors instead on top of pageviews. That would be done by recording $_SERVER['REMOTE_ADDR'] and checking if the visitor has been there recently. You could use 2 counters for hits and unique hits, or some other combination. That’s all I will cover here though so that concludes the article on hit counters, I hope it has been informative.
Custom Math High and Low Functions in PHP
This should be a good beginner tutorial, especially if you have used some functions and if statements and haven’t gone much further. I will explain the concept as we go along, first let’s review the Ternary Operator / Operators that we will use.
$x = $y < 0 ? -1 : 1;
That is sort of a quick “what is the sign” test for signed numbers. If means if y is less than 0 x is negative 1, otherwise it is positive 1. 0 is considered +1 in that case. Following so far? You just need to understand the basic rules so you can understand what is happening in a complex line of code.
$x = $y == 0 ? 0 : ($y < 0 ? -1 : 1);
In that case it mean if y is 0 x is 0, otherwise x is either -1 or +1. Let’s use that principal to make a function that accepts 3 arguments and tells us whether argument 1 is within the bounds of arguments 2 and 3.
function custom_clamp_check($number, $low, $high){
return $number > $high ? false : ($number < $low ? false : true);
}
Think about that function like this, if the first statment is true, we return false, if it isn’t we check the second statment. The function returns false unless the $number is between $high and $low or equal to either. This is intentionally written to work well with floats and integers. Other variable types should not be used.
PHP has built in min and max functions like in this example.
$x = min($y, 0); $x = max(5, 12);
That just gives you the higher number of the two numbers put into the function. Actually you can do max(1, 4, 99, -5) since it allows more arguments, or max(array(1, 4, 99, -5)) with the same result. It returns the highest of whatever is put in. I don’t know if min/max have many pros or cons over statements like we used earlier, but some users have said min/max are slower and less efficient. Regardless of that this article is focusing on using operators in statements to construct the desired functions, even if only for learning purposes.
Our final function is a clamp function, it clamps the value entered to be equal to $high, equal to $low, or between the two.
function custom_clamp($number, $low, $high){
return $number > $high ? $high : ($number < $low ? $low : $number);
}
You should now understand how the function works and what the results will be. custom_clamp(1.0115, 1.0, 0.0) would give you 1.0, the exact high value you put in. These functions are useful for many things, and as I described earlier we can use integers or floats. If a user entered a comment we could check if it’s length is within the range we want.
if(custom_clamp_check(strlen($_GET['comment']), 20, 512) == false){
return "Your comment must be 20 to 512 chars in length.";
}
If the user must also enter a number within 1 and 10 and we want to make sure there are no other numbers possible, we could force it with the clamp function.
$entered_number = custom_clamp(intval($_GET['number']), 1, 10);
I added intval to make this even more strict, since users could have entered 1.0002 and we probably only want whole numbers. The final use shows how useful the function can be in math. The goal is to keep the product above 0 since dividing by zero is not acceptable.
$angle = 1.0 / custom_clamp($radius * pi(), 0.0000001, 1.0);
PHP – What in the world is CType
Apparently the name comes from ctype.h, a file in the C programming language. The PHP engine can execute the code from that file in it’s ctype functions. Does the c in ctype stand for classification, or character maybe? I don’t know, but according to PHP, these functions “are always preferred over regular expressions, and even to some equivalent str_* and is_* functions.” because they are executed from the executable functions (from ctype.h) and are therefore faster.
$is_it_alphanumeric = ctype_alnum("Carnival101"); //true
$is_it_alphanumeric_too = ctype_alnum("Carnival*_*");//false
$is_it_alphanumeric_also = ctype_alnum("Carnival1.01"); //false
ctype_alnum() checks if the string is totally alphanumeric. The first of those was the only one, a decimal is still not going to return true. Checking if things are alphanumeric is actually pretty useful, but it’s probably more common to check if it is an unsigned integer for example.
$is_it_digit = ctype_digit("05909090"); //true
$is_it_digit_too = ctype_digit(-4); //false
$is_it_digit_also = ctype_digit(4.5); //false
So only 0s to 9s will get you a true result. Positive integers will also work. ctype_alpha() is the same as those 2 but for letters only. Going back to ctype_alnum, it also accepts integers but “If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character ” So if you aren’t interested in ASCII tests don’t pass integers to ctype_alnum(). That rule applies to the next function as well, called ctype_print();
ctype_print("asdf\n\r\t"); // false
ctype_print() only returns true if the characters are printable and not control characters. This is a confusing classification, since spaces would be allowed and tabs not. Only use it if you are looking for a very specific type of check. ctype_graph() might be more clear, as it is the same but spaces are not valid, no white space is allowed. ctype_cntrl() is the opposite of ctype_print(), the characters must be control characters to get it to return true.
ctype_lower() returns true for lowercase letters only
ctype_punct() returns true for punctuation only
ctype_space() returns true for white space only (tab, space, newline and so on)
ctype_xdigit() returns true for hexidecimal characters only (comes in useful for checking if the string is a color code for example)
ctype_upper returns true for uppercase letters only
For all these functions, empty strings will give you false in new versions of PHP, but true in older versions (< 5.1). Passing something other than an integer or string will return false.
