php在转换为数组时隐藏属性


php hide attributes on casting to array

我编码了一个php类来表示查询结果。在传入的查询中,我将其转换为数组,将其转换成JSON(每个JSON_encode)并返回给用户。

现在我想定义一个类实习生"debug"属性,它不在输出中——如何在将类强制转换为数组时隐藏属性?

使用unset从结果数组中移除元素。

声明为privateprotected

class Foo
{
   public $bar = 'bar';   
   private $baz = 'baz';
   protected $quux = 'quux';
}
$f = new Foo();
echo json_encode($f);

结果:

{"bar":"bar"}

注:。需要PHP 5,请参阅PHP手册中的"可见性"。