[英]PHP, __get() method, and array parameter
I want to achieve this effect: 我想达到这个效果:
class Foo {
public $bar; // array('aaa' => array('bbb' => 'ccc'))
public function __get($value)
{
return $this->bar[...][key($value)]; // don't know what to implement here
}
}
$obj = new Foo();
$obj->aaa['bbb']; // should return 'ccc'
Is this possible? 这可能吗? How can I do this?
我怎样才能做到这一点?
How can I get to the 'ccc' value from the Foo::$bar array from the inside of the __get() method if I want to call it this way? 如果要以这种方式调用它,如何从__get()方法内部的Foo :: $ bar数组中获取'ccc'值?
Try this: 尝试这个:
<?php
class Foo {
public $bar = array('aaa' => array('bbb' => 'ccc'));
public function __get($value) {
return $this->bar[$value];
}
}
$obj = new Foo();
echo $obj->aaa['bbb'];
will return: 将返回:
ccc
class Foo {
public $bar = array('aaa' => array('bbb' => 'ccc'));
public function __get($value)
{
return $this->bar[$value];
}
}
$obj = new Foo();
var_dump($obj->aaa['bbb']);
Got what you wanted after your edit. 编辑后得到你想要的东西。
<?php
class Foo
{
// note you had: array('aaa' => array('bbb', 'ccc'));
// so `bbb` and `ccc` were values, not keys.
public $bar = array('aaa' => array('bbb' => 'ccc'));
public function __get($name)
{
return $this->bar[$name];
}
}
$obj = new Foo();
echo $obj->aaa['bbb']; // should return 'ccc'
// output: ccc
Not sure from how you phrased the question, but I think this might be what you're looking for? 不确定你如何处理这个问题,但我认为这可能是你在寻找什么?
<?
class Foo {
function __construct(){
$bar = array(
'aaa' => array('bbb' => 'ccc'),
'zzz' => array('yyy' => 'xxx'),
);
foreach($bar as $key => $value){
$this->{$key} = $value;
}
}
public function __get($value){
// return $this->bar[...][key($value)]; // don't know what to implement here
}
}
$obj = new Foo();
echo $obj->aaa['bbb']; // ccc
echo $obj->zzz['yyy']; // xxx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.