Sebastian | 19 Jul 2012 21:22
Picon
Favicon

magic getter

Hi all,

is this a bug, or a feature?

class Foo
{
   private $data;

   public function __get($name)
   {
     return $this->data[$name];
   }
}

$foo = new Foo();
$foo->color = 'red';

echo $foo->color;

I would expect an error, or a least a notice, but it prints out "red" ...

--

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Matijn Woudt | 19 Jul 2012 21:36
Picon

Re: magic getter

On Thu, Jul 19, 2012 at 9:22 PM, Sebastian <php-maillist <at> elygor.de> wrote:
> Hi all,
>
> is this a bug, or a feature?
>
> class Foo
> {
>   private $data;
>
>   public function __get($name)
>   {
>     return $this->data[$name];
>   }
> }
>
> $foo = new Foo();
> $foo->color = 'red';
>
> echo $foo->color;
>
> I would expect an error, or a least a notice, but it prints out "red" ...
>

I guess it's some hidden feature. Since you're not required to declare
your variables in PHP, it's pretty much impossible to detect if this
is what the user wants or an error. In this case, PHP will declare a
public variable color inside the class for you.

- Matijn

(Continue reading)


Gmane