[ create a new paste ] login | about

Link: http://codepad.org/UZtfPQom    [ raw code | output | fork ]

huzia - PHP, pasted on Feb 8:
<?

Class People {
    private $name;

    public function People ($name) {
        $this->name = $name;
    }

    public function __get($name) { 
        if (method_exists($this, 'get'.$name)) { 
            $method = 'get' . $name; 
            return $this->$method(); 
        } else { 
            throw new OutOfBoundsException('Member is not gettable');
        }
    }

    public function __set($name, $value) { 
        if (method_exists($this, 'set'.$name)) { 
            $method = 'set' . $name; 
            $this->$method($value); 
        } else { 
            throw new OutOfBoundsException('Member is not settable');
        }
    }

    private function getName() {
        return $this->name;
    }

    private function setName($value) {
        $this->name = $value;
    }
}

$someone = new People("Andy");

// here goes benchmarking.
echo "Getter with magic method and method_exists: ";
$start = microtime(true);
$somevar = $someone->name;
$end = microtime(true);
echo ($end - $start);
echo " second.\n";

echo "Setter with magic method and method_exists: ";
$start = microtime(true);
$someone->name = "Joel";
$end = microtime(true);
echo ($end - $start);
echo " second.\n";

?>


Output:
1
2
Getter with magic method and method_exists: 0.0004730224609375 second.
Setter with magic method and method_exists: 0.00014305114746094 second.


Create a new paste based on this one


Comments: