Detect if an object property is private in PHP

2019-03-12 04:05发布

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 parent object method is to be used by child objects, I can't simply choose to skip the private properties by name (I won't know what they are in the child objects).

Is there a simple way to detect from within an object which of its properties are private?

Here's a simplified example of what I've got so far, but this output includes the value of $bar:

class testClass {

    public $foo = 'foo';
    public $fee = 'fee';
    public $fum = 'fum';

    private $bar = 'bar';

    function makeString()
    {
        $string = "";

        foreach($this as $field => $val) {

            $string.= " property '".$field."' = '".$val."' <br/>";

        }

        return $string;
    }

}

$test = new testClass();
echo $test->makeString();

Gives the output:

property 'foo' = 'foo'
property 'fee' = 'fee'
property 'fum' = 'fum'
property 'bar' = 'bar' 

I'd like it to not include 'bar'.

If there's a better way to iterate through just the public properties of an object, that would work here too.

8条回答
可以哭但决不认输i
2楼-- · 2019-03-12 04:13

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

查看更多
何必那么认真
3楼-- · 2019-03-12 04:19

You can use Reflection API to check the visibility of properties:

$rp = new \ReflectionProperty($object,$property);
if($rp->isPrivate) {
  // Run if the property is private
} else {
  // Run if the property is Public or Protected
}
查看更多
▲ chillily
4楼-- · 2019-03-12 04:20
$propertyName = 'bar';

if(in_array(propertyName, array_keys(get_class_vars(get_class($yourObject))))) {

}
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-03-12 04:21

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.

查看更多
三岁会撩人
6楼-- · 2019-03-12 04:24

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";
    }
  }
查看更多
老娘就宠你
7楼-- · 2019-03-12 04:25
foreach (get_class_vars(get_class($this)) ....
查看更多
登录 后发表回答