View Single Post
Old 06-18-2006, 02:26 PM   #1 (permalink)
DJMaze
Senior Contributor
 
DJMaze's Avatar
 
Join Date: Mar 2005
Posts: 734
DJMaze is on a distinguished road
Unleash the power of PHP 5

Ok many people are sceptic about PHP 5, many noticed bugs and issues and others unleash the new powers.

WARNING this article is NOT for the PHP savvy who just got his hands on a book like "PHP for dummies". This article explains a big advantage of PHP 5 so you must be familiar with objects and variable types.

First all the code:
PHP Code:
class Readonly
{
    private 
$data# Read only properties
    
public function __construct($data)
    {
        
$this->data $data;
    }
    public function 
__get($key)
    {
        if (isset(
$this->data[$key])) { return $this->data[$key]; }
        
trigger_error('Undefined property: '.$key);
        return 
null;
    }
    public function 
__set($key$val) { throw new Exception('Disallowed to set property: '.$key); }
    public function 
__isset($key) { return isset($this->data[$key]); }
    public function 
__unset($key) { throw new Exception('Disallowed to unset property: '.$key); }
    public function 
get_data() { return $this->data; }

LOL you thought it was big

The class name should already explain what it does. It makes the data inside to be read-only so that a programmer can't overwrite the data.
Why? Well simple, who has ever write code and forgot the second '=' in an expression where it should have been '=='?
Right we all do, and its a pain to track the bug down. Sometimes you don't even notice it

Cool, now tell me, how does it work......
PHP Code:
// The data
$data = array(
    
'var1' => 'value 1',
    
'var2' => 'value 2',
    
'var3' => 'value 3',
);
// Make it read-only
$data = new Readonly($data);

// Read a property
echo 'Value of var1 is: '.$data->var1;

// Test if we can change the value
$data->var1 'foobar'// exception thrown 
Thanks to PHP 5 we now can eliminate some bugs we normaly produce, because every time we try to set a property the script dies on us.
This is something which is NOT possible in PHP 4 and a bug like:
PHP Code:
if ($data['var1'] = 'foo')
{
  
// execute

happens all the time.

I haven't explained bugs but if you all like to know more about this then i will write a follow about the above code including more examples and known bugs.
DJMaze is offline   Reply With Quote