PHP 5.x magic mathods quick question
am 21.08.2009 17:45:41 von Ralph Deffke
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
Re: PHP 5.x magic mathods quick question
am 21.08.2009 18:31:00 von Martin Scotta
--0016e6471194c3c5910471a964e3
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
I think not, but why don't we ask this to 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:
Class Test{
}
$t = new Test;
$t->a = 'b'; # <-- add public property
print_r( $t );
example 2:
Class Test{
private $a;
}
$t = new Test;
$t->a = 'b'; # <-- fatal error
example 3:
Class Test{
private $a;
function __set($name, $value)
{
echo $name, ' <- ', $value, PHP_EOL;
}
}
$t = new Test;
$t->a = 'b'; # <-- trigger __set
example 4:
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 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
--0016e6471194c3c5910471a964e3--