Home  >  Article  >  Backend Development  >  如果让一个对象,可以通过数组模式 和 对象模式 访问其成员属性; 100分

如果让一个对象,可以通过数组模式 和 对象模式 访问其成员属性; 100分

WBOY
WBOYOriginal
2016-06-23 13:39:27898browse

class a{
public $aaa=1;

}

$a=new a();
echo $a->aaa;  //1
同时可以直接:
echo $a['aaa']; //1
  
在PDO中,可以 $db->fetch(PDO::FETCH_LAZY)来实现,这可以说明,PHP是可以做到上述结果的; 请问具体是如何实现的?
求原理,谢谢;


回复讨论(解决方案)

b = 1;$a['b'] = 2;echo $a->b;echo $a['b'];


ArrayObject可以继承,但不允许子类有方法,具体的看手册吧我也不清楚...
说句题外话没恶意,我感觉这玩意没意义...

要写个方法实现。

class a{    public $aaa=1;    function fetch($type){        if($type=='assoc'){            $ret = new stdClass();            $ret->aaa = $this->aaa;        }elseif($type=='array'){            $ret = array();            $ret['aaa'] = $this->aaa;        }        return $ret;    }}$d = new a();$obj = $d->fetch('assoc');var_dump($obj);$arr = $d->fetch('array');var_dump($arr);


object(stdClass)[2]  public 'aaa' => int 1array (size=1)  'aaa' => int 1

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn