Hello,
I'd like to talk about one thing I experienced using __get() magic
method. It is a problem reported for the first time in a bug report
(http://bugs.php.net/bug.php?id=24915) about five years ago but it has
been closed and marked as 'Won't fix'.
Well, this is a sample code for this:
<?php
header('Content-type: text/plain');
class test
{
protected $a;
protected $b = 'test';
public function __get($var)
{
return $this->$var;
}
}
$test = new test;
print 'a: ' . var_export($test->a, true) . ' ' .
var_export(empty($test->a), true) . "\n";
print 'b: ' . var_export($test->b, true) . ' ' .
var_export(empty($test->b), true) . "\n";
?>
This is the current result:
a: NULL
true
b: 'test' true
The expected one should be:
a: NULL
true
b: 'test' false
There is a work-around for this, the vars have just to be assigned to
another ones and then those ones checked with empty(), but of course it
does not satisfy me.
The problem is really annoying. I am sure that there are many other
developers here, who experienced it so I want to know your opinions
about it.
Kuba Wieczorek
Hello,
Le samedi 04 octobre 2008 à 22:59 +0200, Kuba Wieczorek a écrit :
Well, this is a sample code for this:
<?php
header('Content-type: text/plain');class test
{
protected $a;
protected $b = 'test';public function __get($var)
{
return $this->$var;
}
}$test = new test;
print 'a: ' . var_export($test->a, true) . ' ' .
var_export(empty($test->a), true) . "\n";
print 'b: ' . var_export($test->b, true) . ' ' .
var_export(empty($test->b), true) . "\n";
?>This is the current result:
a:NULL
true
b: 'test' trueThe expected one should be:
a:NULL
true
b: 'test' false
Please implement magic method __isset($var) and try again. You'll see it
works fine this way.
Did a little test :
class test {
private $a;
private $b = 'foo';
public function __get($var) {
echo "__get($var)\n";
return $this->$var;
}
public function __isset($var) {
echo "__isset($var)\n";
return isset($this->$var);
}
}
$t = new test();
var_dump($t->a, empty($t->a));
var_dump($t->b, empty($t->b));
Output :
__get(a)
__isset(a)
NULL
bool(true)
__get(b)
__isset(b)
__get(b)
string(3) "foo"
bool(false)
Mark