How to convert (cast) Object to Array without Class Name prefix in PHP?

后端 未结 4 638
被撕碎了的回忆
被撕碎了的回忆 2021-02-10 11:16

How to convert (cast) Object to Array without Class Name prefix in PHP?

class Teste{

    private $a;
    private $b;

    function __construct($a, $b) {
                


        
4条回答
  •  悲哀的现实
    2021-02-10 12:02

    The "class name prefix" is part of the (internal) name of the property. Because you declared both as private PHP needs something to distinguish this from properties $a and $b of any subclass.

    The easiest way to bypass it: Don't make them private. You can declare them as protected instead.

    However, this isn't a solution in every case, because usually one declares something as private with an intention. I recommend to implement a method, that makes the conversion for you. This gives you even more control on how the resulting array looks like

    public function toArray() {
      return array(
        'a' => $this->a,
        'b' => $this->b
      );
    }
    

提交回复
热议问题