PHP Magic faster than simply setting the class attribute?

Posted by Marc Trudel on Stack Overflow See other posts from Stack Overflow or by Marc Trudel
Published on 2010-12-21T04:18:27Z Indexed on 2010/12/21 5:00 UTC
Read the original article Hit count: 244

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about php

Related posts about php5