如何在PHP类中判断变量是公共变量还是私有变量?

时间:2010-02-05 11:14:55

标签: php

我确信如果我知道要搜索什么,我可以在PHP.net上找到它!

基本上我正在尝试遍历类中的所有公共变量。

简化事情:

<?PHP 
class Person
{
  public $name = 'Fred';
  public $email = 'fred@example.com';
  private $password = 'sexylady';

  public function __construct()
  {
    foreach ($this as $key=>$val)
    {
      echo "$key is $val \n";
    }
  }
}

$fred = new Person; 

应该只显示Fred的姓名和电子邮件....

2 个答案:

答案 0 :(得分:6)

使用Reflection。我已经修改了PHP手册中的一个例子来获得你想要的东西:

class Person
{
  public $name = 'Fred';
  public $email = 'fred@example.com';
  private $password = 'sexylady';

  public function __construct()
  {
    $reflect = new ReflectionObject($this);
    foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC) as $prop) 
    {
      $propName = $prop->getName();
      echo $this->$propName . "\n";
    }
  }
}

答案 1 :(得分:0)

http://php.net/manual/en/function.get-class-vars.php

您可以使用get_class_vars()函数:

<?php
class Person
{
    public $name = 'Fred';
    public $email = 'fred@example.com';
    private $password = 'sexylady';

    public function __construct()
    {
        $params = get_class_vars(__CLASS__);
        foreach ($params AS $key=>$val)
        {
            echo "$key is $val \n";
        }
    }
}
?>