开发者

How do I tell if a variable is public or private from within a PHP class?

I'm sure I could find this on PHP.net if only I knew what to search for!

Basically I'm trying to loop through all public variables from within a class.

To simplify things:

<?PHP 
class Person
{
  public $name = 'Fred';
  public $email = 'fred@example.com';
 开发者_StackOverflow中文版 private $password = 'sexylady';

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

$fred = new Person; 

Should just display Fred's name and email....


Use Reflection. I've modified an example from the PHP manual to get what you want:

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";
    }
  }
}


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

You can use get_class_vars() function:

<?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";
        }
    }
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜