Detect if an object property is private in PHP

后端 未结 8 1284
太阳男子
太阳男子 2021-02-04 00:24

I\'m trying to make a PHP (5) object that can iterate through its properties, building an SQL query based only on its public properties, not its private ones.

As this pa

8条回答
  •  时光取名叫无心
    2021-02-04 00:53

    You can use Reflection to examine the properties of the class. To get only public and protected properties, profile a suitable filter to the ReflectionClass::getProperties method.

    Here's a quicky example of your makeString method using it.

    public function makeString()
    {
        $string = "";
        $reflection = new ReflectionObject($this);
        $properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
        foreach ($properties as $property) {
            $name    = $property->getName();
            $value   = $property->getValue($this);
            $string .= sprintf(" property '%s' = '%s' 
    ", $name, $value); } return $string; }

提交回复
热议问题