开发者

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

开发者 https://www.devze.com 2022-12-27 04:48 出处:网络
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:

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

精彩评论

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