我尝试使用类似于array_push
的函数,但是在PHP中使用对象(stdClass)。看看我的期望:
<?php
$obj = new stdClass();
$obj->a = 'foo';
$obj->{'0'} = 'far';
var_dump($obj);
// > object(stdClass)#1 (2) { ["a"]=> string(3) "foo" ["0"]=> string(3) "far" }
var_dump(object_push($obj, 'coin'));
// > object(stdClass)#1 (3) { ["a"]=> string(3) "foo" ["0"]=> string(3) "far" ["1"]=> string(4) "coin" }
答案 0 :(得分:0)
您可以使用此功能object_push
:
function object_push($object, $value) {
$object->{max(array_filter(array_keys((array) $object), 'is_numeric') + [-1]) + 1} = $value;
return $object;
}
然后使用它,就像使用array_push
:
$obj = new stdClass();
$obj->a = 'foo';
$obj->{'0'} = 'far';
var_dump($obj);
// > object(stdClass)#1 (2) { ["a"]=> string(3) "foo" ["0"]=> string(3) "far" }
var_dump(object_push($obj, 'coin'));
// > object(stdClass)#1 (3) { ["a"]=> string(3) "foo" ["0"]=> string(3) "far" ["1"]=> string(4) "coin" }
和平