解决PHP类私有成员 json_encode取不了值的问题

解决PHP类私有成员 json_encode取不了值的问题



use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\SerializerInterface;

class Ml implements JsonSerializable
{

    private $name;
    private $age;

    public function __construct($aParams) {
        foreach ($aParams as $key => $val) {
            if (property_exists($this, $key)) $this->$key = $val;
        }
    }

    /**
     * 生成对象实例
     * 
     * @param array $aParams
     * 
     * @return Ml
     */
    static public function bind(array $aParams)
    {
        $oVO = new Ml($aParams);
        return $oVO;
    }

    public function jsonSerialize() {
        $data = [];
        foreach ($this as $key=>$val)
        {
            if ($val !== null) $data[$key] = $val;
        }
        return $data;
    }

    public static function cc()
    {
        $data = Ml::bind([
            'name'  => 'cc',
            'age'   => '12',
            'me'    => 'ken',
        ]);

        $serializer = SerializerBuilder::create()
                        ->setPropertyNamingStrategy(new IdenticalPropertyNamingStrategy())
                        ->build();

        // print '\n';
        $sdata = $serializer->serialize($data, 'json');

        echo json_encode($sdata);

        echo '
'
; echo json_encode($data); } }

结果

"{\"name\":\"cc\",\"age\":\"12\"}"

{"name":"cc","age":"12"}

你可能感兴趣的:(php,php,json)