Php类属性get和set
我有以下代码Php类属性get和set,php,arrays,Php,Arrays,我有以下代码 <?php class Reg { private $pros = array(); public function __set($key,$val) { $this->pros($key)= $val; } public function __get($key) { return $this->pros($key); } } $reg= new Reg; $reg->t
<?php
class Reg {
private $pros = array();
public function __set($key,$val) {
$this->pros($key)= $val;
}
public function __get($key) {
return $this->pros($key);
}
}
$reg= new Reg;
$reg->tst="tst";
echo $reg->tst;
?>
请说明我错了。谢谢这是因为您正在尝试设置函数返回值
$this->pros($key)
表示调用pros($key)
函数。未将值设置为$pros
数组
语法错误。将值设置为-
改变
$this->pros($key)=$val代码>->$this->pros[$key]=$val代码>
及
或
函数的作用是:用值填充数组,指定键
语法:
array_fill_keys(keys,value);
为什么要使用圆括号,请使用方括号并选中$this->pros[$key]
$array['index'] = 'value';
return $this->pros[$key];
$this->pros[$key] = $value;
$keys = array($key);
$this->pros = array_fill_keys($keys,$value);
array_fill_keys(keys,value);