开发者

Using php's magic function inside another function does not work

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))
    retu开发者_运维百科rn false;
if (empty($this->{$this->sPrimaryKey}))
   return false;
echo 'yaay!';

would this be a php bug?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜