开发者

Check variable is public php

开发者 https://www.devze.com 2023-04-03 20:26 出处:网络
I want to check if a local variable in a class is public or private. The reason is to create a function like this:

I want to check if a local variable in a class is public or private. The reason is to create a function like this:

function ToArray() {
  $arr = array();
  foreach($this as $key => $val) {
    $arr[$key] = $val开发者_StackOverflow社区;
  }
  return $arr;
}

This function also return private fields, and I don't want that. How can I get only public variables here?


From the PHP documentation,

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);

foreach ($props as $prop) {
    print $prop->getName() . "\n";
}

var_dump($props);


To get a list of all public attributes call get_object_vars().

(Hint: calling it by the object itself will return all attributes.)


Make sure to follow some naming convention with your private variables (like i prepend them with _)

Then just return those variables that do not have _ in the beginning of their key.

0

精彩评论

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