The SPL extension allows us to use objects as array. One way to do this is to use the class predefined ArrayObject. Another way is to implement an interface ArrayAccess to access our data as if they were an array. An example of this
class MyArray implements ArrayAccess {
private $data;
public function __construct($array = array())
{
$this->data = $array;
}
public function offsetGet($key)
{
return $this->data[$key];
}
public function offsetSet($key, $value)
{
return $this->data[$key] = $value;
}
public function offsetExists($key)
{
return isset($this->data[$key]);
}
public function offsetUnset($key)
{
unset($this->data[$key]);
}
public function avg()
{
if (count($this->data) > 0)
{
return array_sum($this->data) / count($this->data);
}
}
}
//echo 0xFACEB00C >> 2;
$array = new MyArray(array(1, 2, 3, 4));
echo (int)isset($array[0]);
echo $array[0];
unset($array[1]);
echo (int)isset($array[1]); //throw an ugly notice
echo $array[1];
$array[1] = 4;
echo (int)isset($array[1]);
echo $array[1];
echo $array->avg();
Showing posts with label PHP 5. Show all posts
Showing posts with label PHP 5. Show all posts
Thursday, November 22, 2007
Thursday, October 25, 2007
Autoloading classes
Since PHP 5, it is not necessary to load all classes at the beginning of each script, but if there is a function __autoload is called when they want to use a class that does not exist. This function takes the name of the class you want and it must bear responsibility for making that class exist, in order to avoid the throwing an error because it does not exist.
This is a good step forward for PHP 5, which since version 5.1.2 also gives us the possibility to register multiple functions to do this, rather than simply just one as was previously, through spl_autoload_register.
This is a good step forward for PHP 5, which since version 5.1.2 also gives us the possibility to register multiple functions to do this, rather than simply just one as was previously, through spl_autoload_register.
Subscribe to:
Posts (Atom)