Property overload

<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', '1');

class PropertyOverload{
private $data = array();
public function __set($name,$value){ $this->data[$name] = $value; }
public function __get($name){
if(array_key_exists($name,$this->data)) return $this->data[$name];
$trace = debug_backtrace();
trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'],E_USER_NOTICE);
return null;
}
public function __isset($name){ return isset($this->data[$name]); }
public function __unset($name){ unset($this->data[$name]); }
}

$property_overload = new PropertyOverload;

$property_overload->testprop = 'my test property';
$property_overload->testprop2 = 'my test property2';

echo 'Test: '. $property_overload->testprop;
echo '<br>';

$property_overload->testprop = 'my test property, modified';

echo 'Test: '. $property_overload->testprop;
echo '<br>';

echo 'Test: '. $property_overload->testprop2;
echo '<br>';

echo 'Error: '. $property_overload->testprop3;
?>

//Example using a stdClass instead of an array
class PropertyOverloadOO{
private $data;
public function __construct(){ $this->data = new stdClass(); }
public function __set($name,$value){ $this->data->{$name} = $value; }
public function __get($name){
if(array_key_exists($name,$this->data)) return $this->data->{$name};
$trace = debug_backtrace();
trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'],E_USER_NOTICE);
return null;
}
public function __isset($name){ return isset($this->data->{$name}); }
public function __unset($name){ unset($this->data->{$name}); }
}

0 Comments

You must be logged in to post a comment.