php - magic __get() on end($array) or $var -
i want access last element of array via php's magic __get method.
i using php's end($array) return.
if this:
class fun { protected $var = 'test'; protected $arr = array(1, 2); public function __get($name) { return $this->$name; } public function get_array() { return end($this->arr); } } $obj = new fun(); var_dump($obj->var); //gives me: string(4) "test" var_dump($obj->get_array()); //gives me: int(2);
everything working fine. far good.
i don't want use different "getters" vars , arrays. want method find out if variable or array called , return value.
i thought easy done via $name parameter, too:
class funfun { protected $var = 'more test'; protected $arr = array(1, 2, 3); public function __get($name) { if(is_array($this->$name)) { $ret = end($this->$name); } else { $ret = $this->$name; } return $ret; } } $obj2 = new funfun(); var_dump($obj2->var); //gives me string(9);
but
var_dump($obj2->arr); // gives me: //array(3) {[0]=> int(1) [1]=> int(2) [2]=> int(3)}
if dump within __get() method:
public function __get($name) { if(is_array($this->$name)) { var_dump(end($this->$name)); }
it giving me "right" result: int(3).
am missing something? semantic-error? php's return not designed purpose?
so problem (at least here @ home) seems "get"-call within __construct method. forgot check in original-code.
public function __construct() { $x = $this->arr; var_dump($x); }
gives us:
//array(3) {[0]=> int(1) [1]=> int(2) [2]=> int(3)}
but:
$obj2 = new _funfun(); $x = $obj2->arr; var_dump($x);
shows result: int(3).
i have further ath under 5.3.10-1ubuntu3.17 @ work tomorrow. on home machine 5.6.8 working intended.
Comments
Post a Comment