Php &引用;非法字符串偏移量“;对象属性数组的警告?
我有以下代码:Php &引用;非法字符串偏移量“;对象属性数组的警告?,php,arrays,class,warnings,Php,Arrays,Class,Warnings,我有以下代码: class Foo { public $bar = array(); } $foo = new Foo(); $foo -> bar['count'] = 100; echo $foo -> bar['count']; // 100 $prop = 'bar'; echo $foo -> $prop['count']; // Warning: Illegal string offset 'count' 这给了我一个错误: 警告:在 为什么??如何
class Foo {
public $bar = array();
}
$foo = new Foo();
$foo -> bar['count'] = 100;
echo $foo -> bar['count']; // 100
$prop = 'bar';
echo $foo -> $prop['count']; // Warning: Illegal string offset 'count'
这给了我一个错误:
警告:在
为什么??如何让它工作
===================
我想这样做的原因是:
class Foo {
private $data1 = array();
private $data2 = array();
public function loadData1(array $data) {
return $this -> loadDataInProperty($data, 'data1');
}
public function loadData2(array $data) {
return $this -> loadDataInProperty($data, 'data2');
}
private function loadDataInProperty(array $data, $prop) {
// Filtering, etc.
foreach ($data as $key => $value) {
// Keys comparison, etc.
$this -> $prop[$key] = $value;
}
}
}
基本上,我想将一些数据加载到对象的一个属性(数组)中。有很多不同的数据集。有没有更好/更酷的方法来实现这一点?试试以下方法:
<?php
class Foo {
public $bar = array();
}
$foo = new Foo();
$foo -> bar['count'] = 100;
echo $foo -> bar['count']; // 100
$prop = 'bar';
echo $foo -> {$prop}['count']; // Warning: Illegal string offset 'count'
您对该代码的期望是什么?它很有效!但是为什么呢?这张有官方的PHP文档吗?