Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php魔术方法集_Php_Oop - Fatal编程技术网

php魔术方法集

php魔术方法集,php,oop,Php,Oop,我试图在类上设置一个不明确的变量。大致如下: <?php class MyClass { public $values; function __get($key){ return $this->values[$key]; } function __set($key, $value){ $this->values[$key]=$value; } } $user= new MyClass();

我试图在类上设置一个不明确的变量。大致如下:

<?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"; 
?>

有办法做到这一点吗?

像这样:

您可以使用:

$instance->$dynamicName

您可以使用->操作符访问成员变量

$user->$myvar = "Bar";

如前所述,
$instance->$property
(或
$instance->{$property}
使其跳出)

如果确实希望将其作为数组索引访问,请实现该接口并使用
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

警告:您不能声明
offsetGet
通过引用返回<但是,可以使用code>\uu get(),它允许对
$\u 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
                        )

                )

        )

)

我不敢相信我没试过。谢谢minitech。请告诉我现在流行哪种语言?我想学习流行语言和编写流行代码。