2

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?

10

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Well, this returns array('bbb' => 'ccc'). Somehow, echoing $value inside of the __get() method returns only the "aaa", not the "aaa['bbb']".
@khernik Of cause because this echo $obj->aaa['bbb']; is echo $obj->__get('aaa')['bbb']; and will return your array.
1
<?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

Comments

1
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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.