开发者

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

开发者 https://www.devze.com 2022-12-19 01:08 出处:网络
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.

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

精彩评论

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