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
  • Please post your actual code and no [...] parts. So someone will be able to help you.
    – eisberg
    Nov 29, 2012 at 14:57
  • edited, hope it looks clearer now.
    – khernik
    Nov 29, 2012 at 14:59
  • Why would $obj->aaa['bbb'] return ccc?
    – Prisoner
    Nov 29, 2012 at 14:59
  • According to the deleted post: var_dump($obj->bar['aaa'][1]);...Exactly, can this be $obj->aaa[1]?
    – khernik
    Nov 29, 2012 at 15:00
  • He's trying to convert each array member into an object, it looks like. Nov 29, 2012 at 15:00

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
2
  • Well, this returns array('bbb' => 'ccc'). Somehow, echoing $value inside of the __get() method returns only the "aaa", not the "aaa['bbb']".
    – khernik
    Nov 29, 2012 at 15:17
  • @khernik Of cause because this echo $obj->aaa['bbb']; is echo $obj->__get('aaa')['bbb']; and will return your array.
    – eisberg
    Nov 29, 2012 at 15:18
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
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.

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.