Welcome! Log In Create A New Profile

Advanced

[PHP] magic getter

Posted by Sebastian 
Sebastian
[PHP] magic getter
July 19, 2012 09:30PM
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
Re: [PHP] magic getter
July 19, 2012 09:40PM
On Thu, Jul 19, 2012 at 9:22 PM, Sebastian <[email protected]> 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

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
Jim Lucas
Re: [PHP] magic getter
July 19, 2012 09:40PM
On 07/19/2012 12:22 PM, Sebastian 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" ...
>
>

Their is nothing magical about this.

When you do this:

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

you create a variable within the $foo instance variable called color
with a value of red.

Then, later on when you do this

echo $foo->color;

you are then simply echo'ing the variable/value you created.

with this example, you are never using the __get() magic function to
retrieve the value of color.


--
Jim Lucas

http://www.cmsws.com/
http://www.cmsws.com/examples/
http://www.bendsource.com/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
David Harkness
Re: [PHP] magic getter
July 19, 2012 11:40PM
If you want to block setting of public properties on your class, implement
the magic setter.

class Foo {
private $data = array();

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

function __set($name, $value) {
if ($name != 'foo') {
$this->data[$name] = $value;
}
}
}

$f = new Foo;
$f->x = 5;
echo $f->x; // "5"
$f->foo = 'bar';
echo $f->foo; // Notice: Undefined index: foo in php shell code on
line 1

Enjoy!
David
Sorry, only registered users may post in this forum.

Click here to login