Detect if an object property is private in PHP

后端 未结 8 1258
太阳男子
太阳男子 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:45

    If you cast the object to an array before iterating over it, the private and protected members will have special prefixes:

    class Test{
      public $a = 1;
      private $b = 1;
      protected $c = 1;
    }
    $a = new Test();
    var_dump((array) $a);
    

    displays this:

    array(3) {
      ["a"]=>
      int(1)
      ["Testb"]=>
      int(1)
      ["*c"]=>
      int(1)
    }
    

    There are hidden characters there too, that don't get displayed. But you can write code to detect them. For example, the regular expression /\0\*\0(.*)$/ will match protected keys, and /\0.*\0(.*)$/ will match private ones. In both, the first capturing group matches the member name.

    0 讨论(0)
  • 2021-02-04 00:52

    You can use an array to store public properties, add some wrapper method and use array to insert data to SQL.

    0 讨论(0)
  • 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' <br/>", $name, $value);
        }
        return $string;
    }
    
    0 讨论(0)
  • 2021-02-04 00:53

    Check this code from http://php.net/manual/reflectionclass.getproperties.php#93984

      public function listProperties() {
        $reflect = new ReflectionObject($this);
        foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC /* + ReflectionProperty::IS_PROTECTED*/) as $prop) {
          print $prop->getName() . "\n";
        }
      }
    
    0 讨论(0)
  • 2021-02-04 00:53
    foreach (get_class_vars(get_class($this)) ....
    
    0 讨论(0)
  • 2021-02-04 01:03

    A quicker solution that I found:

    class Extras
    {
        public static function get_vars($obj)
        {
            return get_object_vars($obj);
        }
    }
    

    and then call inside of your testClass:

    $vars = Extras::get_vars($this);
    

    additional reading in PHP.net

    0 讨论(0)
提交回复
热议问题