unset()在类方法中不起作用

时间:2016-02-12 08:15:17

标签: php unset

我有一个班级说Foo,其json字符串属性名为bar[PHP Fiddle Link]

<?php


class Foo {

    public $bar = '{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered","1455261541":"Received Back"}';

    public function getBar(){
        return (array) json_decode($this->bar);
    }

    public function remove($timestamp){

        $newBar = $this->getBar();

        print_r($newBar);

        unset($newBar[$timestamp]);

        print_r($newBar); 

        $this->bar = json_encode($newBar);

    }

}

现在,要从bar中删除元素,我正在执行以下操作,我无法弄清楚它为什么不删除:

$foo = new Foo();
$foo->remove("1455261541");
echo $foo->bar;

打印出来:

Array
(
    [1455260079] => Tracking : #34567808765098767 USPS
    [1455260723] => Delivered
    [1455261541] => Received Back
)
Array
(
    [1455260079] => Tracking : #34567808765098767 USPS
    [1455260723] => Delivered
    [1455261541] => Received Back
)
{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered","1455261541":"Received Back"}

这背后的原因是什么?有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

尝试下面的解决方案,我刚刚更改了getBar函数并在json_decode函数中添加了一个参数:

class Foo {

    public $bar = '{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered","1455261541":"Received Back"}';

    public function getBar(){
        return json_decode($this->bar, true);
    }

    public function remove($timestamp){

        $newBar = $this->getBar();

        print_r($newBar);

        unset($newBar[$timestamp]);

        print_r($newBar);

        $this->bar = json_encode($newBar);

    }

}

$foo = new Foo();
$foo->remove("1455261541");
echo $foo->bar;

输出:

Array
(
    [1455260079] => Tracking : #34567808765098767 USPS
    [1455260723] => Delivered
    [1455261541] => Received Back
)
Array
(
    [1455260079] => Tracking : #34567808765098767 USPS
    [1455260723] => Delivered
)
{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered"}