Location: PHPKode > scripts > Java and C# compatible object autoboxing > autoboxExample_TypeEnforcing.php
<?php

/**
 * JAVA Autoboxing (part of Lotos Framework)
 *
 * Copyright (c) 2005-2010 Artur Graniszewski (hide@address.com) 
 * All rights reserved.
 * 
 * @category   Library
 * @package    Lotos
 * @subpackage DataTypes
 * @copyright  Copyright (c) 2005-2010 Artur Graniszewski (hide@address.com)
 * @license    GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007
 * @version    $Id$
 */

 
// load required library
include("./variablesManager.php");

   /**
 * Example class.
 * 
 * Note: in order to use AutoBoxing, your class need to extend "AutoBoxedObject" class.
 */
class Integer extends AutoBoxedObject
{
    public $value = 0;
    
    public function __construct($value) {
        
        // TYPE ENFORCING
        if($value && !is_int ($value) && !is_float($value)) {
            throw new Exception('The new value is not an Integer!!!');
        }
        
        $this->value = (int)$value;
    }
    
    public function __toString() {
        // NOTE: this must be a string, PHP forbids returning different type of variables in __toString() methods.
        return "{$this->value}";
    }
    
    public function toHex() {
        $x = strtoupper(dechex($this->value));
        $y = ceil(strlen($x) / 2);
        return str_pad($x, $y * 2, '0', STR_PAD_LEFT);
    }
}

/**
* Initializes a newly created Integer object.
* @return Integer created String object
*/
function & integer($value = null) {
    $x = & VariablesManager::getNewPointer(new Integer($value));
    return $x;
}

// 1) We're setting $x as an Integer object
$x = & integer();

// 2) Now we are changing $x value to 10
//    NOTE: PHP without enabled autoboxing would destroy the Integer object and set $x as simple integer type
$x = 10;

// 3) Now we are checking, that $x is still an object
echo "<h3>Integer autoboxing:</h3>";
echo 'The initial value of $x variable is "'.$x.'"<br />';
echo 'The initial datatype of $x variable is '.gettype($x).(is_object($x) ? ' ('.get_class($x).')': '').'<br />';
//   this line would raise FATAL_ERROR withou autoboxing:
echo 'The hex value of $x is 0x'.$x->toHex().'<br />';

// 4) Now we are trying to change $x value to a invalid integer value 
echo "<h3>Type enforcing:</h3>";
try {
    $x = "aaaa"; // invalid value, valid integer should contain digits only
} catch (Exception $e) {
    echo 'Exception detected: Cannot change the integer value of $x to "aaaa", the new value should contain digits only<br />';
    echo "Original exception message: ".$e->getMessage()."<br />";
}



// 5) Lets do some math...
echo "<h3>Basic math:</h3>";

echo '<strong>Impossible becomes possible: adding two objects in PHP</strong>:<br />';
$x = & integer(0);
$y = & integer(10);
$z = & integer(20);

//   PLEASE NOTE the quotes surrounding the variables names, without it PHP would return '1' instead the true
//         value of integers objects (because it would not use __toString() method to do the math!)
$x = "$y" + "$z" + 5;
echo 'The initial value of $y variable is "'.$y.'"<br />';
echo 'The initial datatype of $y variable is '.gettype($y).(is_object($y) ? ' ('.get_class($y).')': '').'<br />';
echo 'The initial value of $z variable is "'.$z.'"<br />';
echo 'The initial datatype of $z variable is '.gettype($z).(is_object($z) ? ' ('.get_class($z).')': '').'<br />';
echo '<u>The result of $x = $y + $z + 5 is "'.$x.'"</u><br />';
echo 'The datatype of $x (sum) variable is '.gettype($x).(is_object($x) ? ' ('.get_class($x).')': '').'<br />';
//   this line would raise a FATAL_ERROR without autoboxing enabled:
echo 'The hex value of $x is 0x'.$x->toHex().'<br />';


echo '<br /><strong>We can also do other math operations, for example divide two objects: </strong><br />';
$x = & integer(0);
$y = & integer(20);
$z = & integer(10);

//   PLEASE NOTE the quotes surrounding the variables names, without it PHP would return '1' instead the true
//         value of integers objects (because it would not use __toString() method to do the math!)
$x = "$y" / "$z";

echo 'The initial value of $y variable is "'.$y.'"<br />';
echo 'The initial value of $z variable is "'.$z.'"<br />';
echo '<u>The result of $x = $y / $z  is "'.$x.'"</u><br />';
echo 'The hex value of $x is 0x'.$x->toHex().'<br />';

echo '<br /><strong>This behaviour gives us some new C-like functionality</strong><br />';
$x = & integer(0);
$y = & integer(20);
$z = & integer(7);

//   PLEASE NOTE the quotes surrounding the variables names, without it PHP would return '1' instead the true
//         value of integers objects (because it would not use __toString() method to do the math!)
$x = "$y" / "$z";

echo 'The initial value of $y variable is "'.$y.'"<br />';
echo 'The initial value of $z variable is "'.$z.'"<br />';
echo '<u>The result of $x = $y / $z  is "'.$x.'"</u><br />';
echo 'The hex value of $x is 0x'.$x->toHex().'<br />';

echo "Why 2.00 and not 2.85? Because in C and C# operation: 20 / 7 = 2.85 converted to int becomes 2<br />";
echo "Ofcourse you can freely change this behaviour in your custom Integer class<br />";

echo "<h3>Remember, you can easily create your own data types, like float, double, utf-8 string, etc.!</h3>";
echo "...using this mechanism you can even try to override default mathematical operators like +/*-!<br />";

Return current item: Java and C# compatible object autoboxing