# __get() magic method and its use with empty() function.

- Thread: https://externals.io/message/40860
- Original archive: https://news-web.php.net/php.internals/40860
- Started by Kuba Wieczorek on 2008-10-04T20:59:29+00:00
- Messages: 2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #40860 — Kuba Wieczorek — 2008-10-04T20:59:29+00:00

URL: https://externals.io/message/40860#40860

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

---

## #40861 — karpeles@ookoo.org — 2008-10-04T22:01:25+00:00

URL: https://externals.io/message/40860#40861 · In reply to: #40860

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' true
> 
> The 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
