简体   繁体   English

php magic method __set

[英]php magic method __set

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? 有办法做到这一点吗?

As has been stated $instance->$property ( or $instance->{$property} to make it jump out ) 正如已经说明$instance->$property$instance->{$property}使它跳出来

If you really want to access it as an array index, implement the ArrayAccess interface and use offsetGet() , offsetSet() , etc. 如果您确实想要将其作为数组索引访问,请实现ArrayAccess接口并使用offsetGet()offsetSet()等。

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. 警告 :您不能声明offsetGet通过引用返回。 __get() , however, can be which permits nested array element access of the $_data property, for both reading and writing. 但是, __get()可以允许嵌套数组元素访问$_data属性,用于读取和写入。

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
                        )

                )

        )

)

Like so: http://ideone.com/gYftr 像这样: http//ideone.com/gYftr

You'd use: 你用的是:

$instance->$dynamicName

您可以使用 - >运算符访问成员变量。

$user->$myvar = "Bar";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM