PHP Magic faster than simply setting the class attribute?
- by Marc Trudel
Well, not exactly that, but here is an example. Can anyone explain the difference between B and C? How can it be faster to use a magic function to dynamically set a value instead of simply setting the value in the attribute definition?
Here is some code:
[root@vm-202-167-238-17 ~]# cat test.php; for d in A B C; do echo "------"; ./test.php $d; done;
#!/usr/bin/php
<?php
$className = $argv[1];
class A
{
public function __get($a)
{
return 5;
}
}
class B
{
public $a = 5;
}
class C
{
public function __get($a)
{
$this->a = 5;
return 5;
}
}
$a = new $className;
$start = microtime(true);
for ($i=0; $i < 1000000; $i++)
$b = $a->a;
$end = microtime(true);
echo (($end - $start) * 1000) ." msec\n";
------
598.90794754028 msec
------
205.48391342163 msec
------
189.7759437561 msec