检测PHP中的对象属性是否为私有属性

Hip*_*jim 22 php oop properties

我正在尝试创建一个PHP(5)对象,它可以遍历其属性,仅基于其公共属性而不是私有属性构建SQL查询.

由于这个父对象方法将由子对象使用,我不能简单地选择按名称跳过私有属性(我不知道它们在子对象中是什么).

是否有一种简单的方法可以从对象中检测哪些属性是私有的?

这是我到目前为止所得到的简化示例,但此输出包含$ 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();
Run Code Online (Sandbox Code Playgroud)

给出输出:

property 'foo' = 'foo'
property 'fee' = 'fee'
property 'fum' = 'fum'
property 'bar' = 'bar' 
Run Code Online (Sandbox Code Playgroud)

我希望它不包括'bar'.

如果有更好的方法来迭代对象的公共属性,那么这也适用.

pow*_*tac 19

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";
    }
  }
Run Code Online (Sandbox Code Playgroud)

  • 这正是我所需要的.谢谢你的教训! (2认同)

sal*_*the 12

您可以使用Reflection来检查类的属性.要仅获取公共属性和受保护属性,请为该ReflectionClass::getProperties方法配置合适的过滤器.

以下是makeString使用它的方法的快速示例.

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;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

我找到了一个更快的解决方案:

class Extras
{
    public static function get_vars($obj)
    {
        return get_object_vars($obj);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的 testClass 内部调用:

$vars = Extras::get_vars($this);
Run Code Online (Sandbox Code Playgroud)

PHP.net 中的附加阅读