Re: PHP 5.x magic mathods quick question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I think not, but why don't we ask this to PHP ?

<?php

class Foo{}
$foo = new Foo;

var_dump(
    method_exists( $foo, '__set' )
);
?>

*<< __set()* is run when writing data to inaccessible members. >>
http://php.net/__set

So, I think that when you write data to an non-existent member php will
first try is the object has an __set method, if not it'll raise a Fatal
Error

example 1:
<?php
Class Test{
 }

$t = new Test;
$t->a = 'b'; # <-- add public property
print_r( $t );

example 2:
<?php
Class Test{
    private $a;
}

$t = new Test;
$t->a = 'b'; # <-- fatal error

example 3:
<?php
Class Test{
    private $a;

    function __set($name, $value)
    {
        echo $name, ' <- ', $value, PHP_EOL;
    }
}

$t = new Test;
$t->a = 'b'; # <-- trigger __set

example 4:
<?php
Class Test{
    public $a;
    private $c;
    function __set($name, $value)
    {
        echo $name, ' <- ', $value, PHP_EOL;
    }
}

$t = new Test;
$t->a = '1'; # <-- set the public property (don't trigger __set)
$t->b = '2'; # <-- trigger __set (property does not exists)
$t->c = '3'; # <-- trigger __set (property is private)

print_r( $t );


On Fri, Aug 21, 2009 at 12:45 PM, Ralph Deffke <ralph_deffke@xxxxxxxx>wrote:

> do I understand the doc right, that magic methods do exist in any object?
> creating one (like __set() ) ovewrites the standard one?
>
>
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


-- 
Martin Scotta

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux