Using php magic function inside another function doesn't work

I want to use the magic function __set() and __get() to store SQL data inside the php5 class, and I get some strange problems using them inside the 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!'; 

will it be php error?

+4
source share
1 answer

empty () first * calls the __isset () method, and only if it returns true the __get () method. those. your class should also implement __isset ().

eg.

 <?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 cannot "directly" find an available property in hashtable for the property of the object.

+6
source

Source: https://habr.com/ru/post/1307040/


All Articles