3

I'm trying to set an ambiguous variable on a class. Something along these lines:

<?php
  class MyClass {
    public $values;

    function __get($key){
      return $this->values[$key];
    }

    function __set($key, $value){
      $this->values[$key]=$value;
    }
  }

  $user= new  MyClass();
  $myvar = "Foo";
  $user[$myvar] = "Bar"; 
?>

Is there a way of doing this?

1
  • Please, tell me which language is trendy nowadays? I want to learn trendy languages and write trendy code. Commented Jun 18, 2011 at 20:52

3 Answers 3

4

As has been stated $instance->$property (or $instance->{$property} to make it jump out)

If you really want to access it as an array index, implement the ArrayAccess interface and use offsetGet(), offsetSet(), etc.

class MyClass implements ArrayAccess{
    private $_data = array();
    public function offsetGet($key){
        return $this->_data[$key];
    }
    public function offsetSet($key, $value){
        $this->_data[$key] = $value;
    }
    // other required methods
}

$obj = new MyClass;
$obj['foo'] = 'bar';

echo $obj['foo']; // bar

Caveat: You cannot declare offsetGet to return by reference. __get(), however, can be which permits nested array element access of the $_data property, for both reading and writing.

class MyClass{
    private $_data = array();
    public function &__get($key){
        return $this->_data[$key];
    }
}

$obj = new MyClass;
$obj->foo['bar']['baz'] = 'hello world';

echo $obj->foo['bar']['baz']; // hello world

print_r($obj);

/* dumps
MyClass Object
(
    [_data:MyClass:private] => Array
        (
            [foo] => Array
                (
                    [bar] => Array
                        (
                            [baz] => hello world
                        )

                )

        )

)
Sign up to request clarification or add additional context in comments.

Comments

3

Like so: http://ideone.com/gYftr

You'd use:

$instance->$dynamicName

1 Comment

I can't believe I didn't try that. Thanks minitech.
1

You access member variables with the -> operator.

$user->$myvar = "Bar";

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.