更改作为数组的属性条目的最快捷方式是什么。
// Generates Illegal string offset ...
$this->propertyArray['index'] = 'xxx';
我忘了提到动态访问该属性,这是一个完整的片段:
class MyObject {
public $dimensions = [
'width' => 100,
'height' => 200
];
public function changeEntryOfArrayProperty($property, $entry, $value) {
// Warning: Illegal string offset 'width'
$this->$property[$entry] = $value;
}
}
$obj = new MyObject();
// Warning: Illegal string offset 'width'
$obj->changeEntryOfArrayProperty('dimensions', 'width', 600);
答案 0 :(得分:0)
您需要更改访问动态媒体资源的方式 - 请参阅Dynamically access an object property array element in PHP
public function changeEntryOfArrayProperty($property, $entry, $value) {
// Warning: Illegal string offset 'width'
$this->{$property}[$entry] = $value;
}
答案 1 :(得分:0)
我发现'ArrayObject'对于这些技术非常有用。唉,我不完全理解它是如何运作的。我怀疑它是PHP所知道的“特殊对象”,因为它解决了数组下标问题,据我所知,“普通”类无法使用它。
我提供代码。它可能很有用。
<?php
class MyObject extends \ArrayObject {
// public $dimensions = null;
public function changeEntryOfArrayProperty($property, $entry, $value) {
// Warning: Illegal string offset 'width'
if (!isset($this->{$property})) {
$this->{$property} = array();
}
$this->{$property}[$entry] = $value;
}
public function __construct($initValues =
array('dimensions' => array('width' => 100,
'height' => 200)))
{
parent::__construct($initValues, \ArrayObject::ARRAY_AS_PROPS);
}
}
$obj = new MyObject();
// Warning: Illegal string offset 'width'
$obj->changeEntryOfArrayProperty('dimensions', 'width', 600);
$obj->changeEntryOfArrayProperty('hello', 'there', 'world');
var_dump($obj);
var_dump($obj->dimensions['width']);
var_dump($obj->hello['there']);
// ------- access the properties and arrays directly...
$obj->newProperty = array();
$obj->newProperty['NP1'] = 'new property 1';
var_dump($obj->newProperty, $obj->newProperty['NP1']);
输出:
object(MyObject)[1]
public 'dimensions' =>
array
'width' => int 600
'height' => int 200
public 'hello' =>
array
'there' => string 'world' (length=5)
int 600
string 'world' (length=5)
array
'NP1' => string 'new property 1' (length=14)
string 'new property 1' (length=14)