views:

119

answers:

1

I want to use magic function __set() and __get() for storing SQL data inside a php5 class and I get some strange issue using them inside a function:

Works:

if (!isset($this->sPrimaryKey) || !isset($this->sTable))
 return false;
$id = $this->{$this->sPrimaryKey};
if (empty($id))
 return false;
echo 'yaay!';

Does not work:

if (!isset($this->sPrimaryKey) || !isset($this->sTable))
    return false;
if (empty($this->{$this->sPrimaryKey}))
   return false;
echo 'yaay!';

would this be a php bug?

+6  A: 

empty() first* calls the __isset() method and only if it returns true the __get() method. i.e. your class has to implement __isset() as well.

E.g.

<?php
class Foo {

  public function __isset($name) {
    echo "Foo:__isset($name) invoked\n";

    return 'bar'===$name;
  }

  public function __get($name) {
    echo "Foo:__get($name) invoked\n";
    return 'lalala';
  }
}

$foo = new Foo;
var_dump(empty($foo->dummy));
var_dump(empty($foo->bar));

prints

Foo:__isset(dummy) invoked
bool(true)
Foo:__isset(bar) invoked
Foo:__get(bar) invoked
bool(false)

* edit: if it can't "directly" find an accessible property in the object's property hashtable.

VolkerK
works!! Thank you!! :D
Sirber
Did PHP4 offer `__isset`?
LeguRi
@Richard: no. `5.1.0 Added __isset() and __unset().`
Sirber
Thanks! +1 - this has proven to be very valuable information for me...
LeguRi