Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Достаточно много видел разных вариантов реализации возможностей которые есть в обычных ОО языках (Delphi, Java, ActionScript) — и которых частенько не хватает php. А именно get & set методы.
// определения классов Object и Rectangle
<...>
// Стандартный аналог
class Rectangle2
{
public $width = 400;
public $height = 1;
public function getArea(){
return $this->width*$this->height;
}
}
$iterations = 10000;
echo "Let's perform $iterations simple iterations!\n";
$r = new Rectangle();
$t = microtime(true);
for ($i = 0; $i < $iterations; ++$i) {
$r->height++;
$r->height - $r->width - $r->area;
}
echo "Advanced class took ".round($res = microtime(true) - $t, 3)." sec\n";
$r = new Rectangle2();
$t = microtime(true);
for ($i = 0; $i < $iterations; ++$i) {
$r->height++;
$r->height - $r->width - $r->getArea();
}
echo "Standard class took ".round($res2 = microtime(true) - $t, 3)." sec\n";
echo "Difference: ", round($res/$res2, 2), " times!\n";
$ php test.php Let's perform 10000 simple iterations! Advanced class took 1.323 sec Standard class took 0.102 sec Difference: 13.03 times!
$getterMethod = 'get' . ucfirst($name);
class MyRectangle extends Rectangle{
}
$mr = new MyRectangle();
echo $mr->height;
// выше используем код из примера к публикации
$rect->height=1000;
var_export(isset($rect->height));
public function __isset($name)
{
$getter='get'.$name;
if(method_exists($this,$getter)){
return $this->$getter()!==null;
}elseif(property_exists($this,$name)){
return true;
}
return false;
}
$rect->height=1000;
var_export(isset($rect->height));
var_export(isset($rect->weight));
Getters/Setters getting real